sql – PostGis最近邻查询

前端之家收集整理的这篇文章主要介绍了sql – PostGis最近邻查询前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想检索另一组点的给定范围内的所有点.比方说,找到距离任何地铁站500米范围内的所有商店.

我写了这个查询,这很慢,并且想要优化它:

  1. SELECT DISCTINCT ON(locations.id) locations.id FROM locations,pois
  2. WHERE pois.poi_kind = 'subway'
  3. AND ST_DWithin(locations.coordinates,pois.coordinates,500,false);

我正在运行最新版本的Postgres和PostGis(Postgres 9.5,PostGis 2.2.1)

这是表元数据:

  1. Table "public.locations"
  2. Column | Type | Modifiers
  3. --------------------+-----------------------------+--------------------------------------------------------
  4. id | integer | not null default nextval('locations_id_seq'::regclass)
  5. coordinates | geometry |
  6. Indexes:
  7. "locations_coordinates_index" gist (coordinates)
  8.  
  9.  
  10. Table "public.pois"
  11. Column | Type | Modifiers
  12. -------------+-----------------------------+---------------------------------------------------
  13. id | integer | not null default nextval('pois_id_seq'::regclass)
  14. coordinates | geometry |
  15. poi_kind_id | integer |
  16. Indexes:
  17. "pois_pkey" PRIMARY KEY,btree (id)
  18. "pois_coordinates_index" gist (coordinates)
  19. "pois_poi_kind_id_index" btree (poi_kind_id)
  20. Foreign-key constraints:
  21. "pois_poi_kind_id_fkey" FOREIGN KEY (poi_kind_id) REFERENCES poi_kinds(id)

这是EXPLAIN(ANALYZE,BUFFERS)的结果:

  1. Unique (cost=2407390.71..2407390.72 rows=2 width=4) (actual time=3338.080..3338.252 rows=918 loops=1)
  2. Buffers: shared hit=559
  3. -> Sort (cost=2407390.71..2407390.72 rows=2 width=4) (actual time=3338.079..3338.145 rows=963 loops=1)
  4. Sort Key: locations.id
  5. Sort Method: quicksort Memory: 70kB
  6. Buffers: shared hit=559
  7. -> Nested Loop (cost=0.00..2407390.71 rows=2 width=4) (actual time=2.466..3337.835 rows=963 loops=1)
  8. Join Filter: (((pois.coordinates)::geography && _st_expand((locations.coordinates)::geography,500::double precision)) AND ((locations.coordinates)::geography && _st_expand((pois.coordinates)::geography,500::double precision)) AND _st_dwithin((pois.coordinates)::geography,(locations.coordinates)::geography,500::double precision,false))
  9. Rows Removed by Join Filter: 4531356
  10. Buffers: shared hit=559
  11. -> Seq Scan on locations (cost=0.00..791.68 rows=24168 width=36) (actual time=0.005..3.100 rows=24237 loops=1)
  12. Buffers: shared hit=550
  13. -> Materialize (cost=0.00..10.47 rows=187 width=32) (actual time=0.000..0.009 rows=187 loops=24237)
  14. Buffers: shared hit=6
  15. -> Seq Scan on pois (cost=0.00..9.54 rows=187 width=32) (actual time=0.015..0.053 rows=187 loops=1)
  16. Filter: (poi_kind_id = 3)
  17. Rows Removed by Filter: 96
  18. Buffers: shared hit=6
  19. Planning time: 0.184 ms
  20. Execution time: 3338.304 ms
  21. (20 rows)

解决方法

我认为您使用的是st_dwithin的地理版本,因为第四个参数.

尝试将您的查询更改为此查询

  1. SELECT DISCTINCT ON(locations.id) locations.id FROM locations,500);

如果没有解决,请再次发布解释分析.

猜你在找的MsSQL相关文章