为什么我的 postgis 不在几何字段上使用索引?

Why my postgis not use index on geometry field?

postgresql 9.5 + postgis 2.2 windows。 我首先创建一个 table:

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

然后,添加几何字段 'geom':

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

并在其上创建要点索引:

CREATE INDEX points_index_geom ON points USING GIST (geom);

然后,我将大约 1,000,000 个点插入 table。

我想查询距给定点给定距离内的所有点。 这是我的 sql 代码:

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

结果是我想要的,就是太慢了。 当我 explain analyze verbose 处理这段代码时,我发现它没有使用 points_index_geom (解释显示序列扫描并且没有索引)。

所以我想知道为什么它不使用索引,我应该如何改进?

您不能期望 ST_Distance_Sphere() 对此查询使用索引。您正在对 geom 字段的内容进行计算,然后对计算结果进行比较。在这种情况下,数据库可能不会使用索引,除非您有一个函数索引可以执行与查询中几乎相同的计算。

查找距某个点给定距离的位置的正确方法是使用 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.

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