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

标签 postgresql indexing postgis

Windows 上的 postgresql 9.5 + postgis 2.2。 我首先创建一个表:

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 个点。

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

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

结果是我想要的,但是太慢了。 当我在这段代码上解释分析详细时,我发现它没有使用points_index_geom(解释显示seq扫描并且没有索引)。

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

最佳答案

您不能期望 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.

关于postgresql - 为什么我的 postgis 不在几何字段上使用索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38968349/

相关文章:

ruby-on-rails - 可以在 Heroku 上拥有一个动态使用不同数据库的应用程序吗?

postgresql - 如何将 CakePHP 连接到 Postgres 数据库?

sql - 仅选择组中所有元素都具有相同值的组

Postgresql Ubuntu 的奇怪行为(版本不兼容?)

Python 多进程 - 索引多个返回

PostgreSQL (shp2pgsql) AddGeometryColumn 给出 "No function matches the given name"

python - Pandas - 计算所有列的 z 分数

jquery - 循环遍历 div 内的某些元素

java - BasicDataSource 找不到 postgresql 或 postgis jdbc 驱动程序

postgresql - 将两个数据字段插入到具有相同投影的 PostGis 中的单个数据字段中