首页 > 关于postgis,为什么查询不走索引

关于postgis,为什么查询不走索引

SQL

sqlselect
    *,
    st_distance_sphere(
                       geometry(poi),
                       geometry('POINT(116.41739 39.913164)')
                      ) distance
from
    test
order by
    distance asc
limit
    10

EXPLAIN结果:

Limit  (cost=14826.00..14826.02 rows=10 width=51)
  ->  Sort  (cost=14826.00..14950.85 rows=49939 width=51)
        Sort Key: (_st_distance(geography(geometry(poi)), '0101000020E61000005BEB8B84B61A5D4039F1D58EE2F44340'::geography, 0::double precision, false))
        ->  Seq Scan on test  (cost=0.00..13746.83 rows=49939 width=51)

已经给poi建立了gist索引了……为啥却没用呢?
才12w数据,检索却要0.6s

表结构

id serial8 primary key not null,

name varchar(80) not null default '',

poi st_geometryfromtext('POINT(112.123, 23.111)',4326)

索引

create index poi on test using gist(poi)


你这个问题至少应该把表结构和索引定义给出来

postgersql会根据实际数据的情况来规划查询,你可以试试关闭顺序扫描(enable_seqscan )来强制pg使用索引

如果从100000行中选1000行是使用索引的好时机, 那么从100行中选1行很难说也需要索引,因为100行很可能是装在一个磁盘页里面的,因此没有任何查询规划能比通过顺序访问抓取一个磁盘页面更有效。

见 http://www.highgo.com.cn/docs/docs90cn/indexes-examine.html


自问自答:

正确的SQL应该是:

sqlselect
    *,
    st_distance_sphere(poi,
                       st_geometryfomtext('POINT(116.41739 39.913164)',4326)
                      ) distance
from
    test
order by
    st_geometryfromtext('point(116.41739 39.913164)',4326) <-> poi
limit
    10
【热门文章】
【热门文章】