Why my postgis not use index on geometry field?

£可爱£侵袭症+ 提交于 2019-12-11 02:32:37

问题


postgresql 9.5 + postgis 2.2 on windows. I firstly create a table:

CREATE TABLE points (
  id   SERIAL,
  ad   CHAR(40),
  name VARCHAR(200)
);

then, add a geometry field 'geom':

select addgeometrycolumn('points', 'geom', 4326, 'POINT', 2);

and create gist index on it:

CREATE INDEX points_index_geom ON points USING GIST (geom);

then, I insert about 1,000,000 points into the table.

I want to query all points that within given distance from given point. this is my sql code:

SELECT st_astext(geom) as location FROM points
WHERE st_distance_sphere(
     st_geomfromtext('POINT(121.33 31.55)', 4326),
     geom) < 6000;

the result is what I want, but it is too slow. when I explain analyze verbose on this code, I found it dose not use points_index_geom (explain shows seq scan and no index).

So i want to know why it dose not use index, and how should i improve?


回答1:


You cannot expect ST_Distance_Sphere() to use an index on this query. You are doing a calculation on the contents of the geom field and then you are doing a comparison on the calculation result. Databases may not use an index in such a scenario unless you have a function index that does pretty much the same calculation as in your query.

The correct way to find locations with in a given distance from some point is to use ST_DWithin

ST_DWithin — Returns true if the geometries are within the specified distance of one another. For geometry units are in those of spatial reference and For geography units are in meters and measurement is defaulted to use_spheroid=true (measure around spheroid), for faster check, use_spheroid=false to measure along sphere.

and

This function call will automatically include a bounding box comparison that will make use of any indexes that are available on the geometries.



来源:https://stackoverflow.com/questions/38968349/why-my-postgis-not-use-index-on-geometry-field

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