Slow query when comparing geometries

ぐ巨炮叔叔 提交于 2019-12-12 19:07:25

问题


I am trying to compare and create a new table. But its taking more time to compare.

Table 1 (schema)

+-------------+----------+-------------+
| Column      | Type     | Modifiers   |
|-------------+----------+-------------|
| line_id     | bigint   |             |
| junction    | integer  |             |
| geom        | geometry |             |
+-------------+----------+-------------+
Indexes:
    "points_geom_gix" gist (geom)

Where junction contains either 0 or 1.

Table 2

+----------+----------+-------------+
| Column   | Type     | Modifiers   |
|----------+----------+-------------|
| line_id  | bigint   |             |
| geom     | geometry |             |
+----------+----------+-------------+
Indexes:
    "jxn_geom_gix" gist (geom)

I want to create a new table table 3 by comparing geometries of two tables.

Condition

  • Select geom from both tables where two geometries are equal.
  • Select geom from table1 where junction = 1 and and geom not present in table 3.

I tried like below

CREATE TABLE table3 as select a.geom from table1 a, table2 b where st_equals(a.geom,b.geom);

(create gist index on geom column of table3)

and

INSERT INTO table3 SELECT a.geom from table1 a, table3 b where a.junction = 1 and NOT st_equals(a.geom,b.geom);

But second query is taking huge time.

Will someone help me in optimizing query?


回答1:


With your last sql you produce nearly cartesian result. For example if you have 10 000 geometries with junciton =1 in table1 that not existing in table3, and in table 3 you have already 10 000 other geometries then for every geometry with juncition=1 you return 10 000 rows. In such situation when you want to find some row that is not in other table use EXISTS clause it will not multiple your results and will not produce cartesian.

INSERT INTO table3 
SELECT a.geom 
  from table1 a
 where a.junction = 1 
   and NOT exists (select from table3 b 
                    where st_equals(a.geom,b.geom)
                      and st_DWithin(a.geom, b.geom,0));

I edited query - added st_Dwithin(a.geom, b.geom,0) it should make query even faster as not exists should compare only these geoms that are in 0 distance between them (if there is no 0 distance between them for sure there are not equal). Generaly st_dwithin will use gist indexes to filter geoms that are not close enough to be equal.



来源:https://stackoverflow.com/questions/45275267/slow-query-when-comparing-geometries

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!