Stu*_*tuR 4 postgresql index postgresql-9.3
\d 聚合
Materialized view "public.aggregate"
Column | Type | Modifiers
------------------+-----------------------------+-----------
id | integer |
searchable | text |
name | character varying(255) |
source_type | character varying(255) |
source_id | integer |
latitude | double precision |
longitude | double precision |
created_at | timestamp without time zone |
updated_at | timestamp without time zone |
Indexes:
"aggregate_lat_lng_point" gist (point(latitude, longitude))
"searchable_tsvector" gin (to_tsvector('english'::regconfig, COALESCE(searchable, ''::text)))
Run Code Online (Sandbox Code Playgroud)
询问:
EXPLAIN ANALYZE SELECT name FROM aggregate
WHERE point(53.574753, -2.1) <@> point(latitude, longitude) < 100;
Run Code Online (Sandbox Code Playgroud)
结果:
Seq Scan on aggregate_mv (cost=0.00..23.01 rows=172 width=516) (actual time=0.019..0.522 rows=458 loops=1)
Filter: (('(53.574753,-2.1)'::point <@> point(latitude, longitude)) < 100::double precision)
Rows Removed by Filter: 320
Total runtime: 0.579 ms
(4 rows)
Run Code Online (Sandbox Code Playgroud)
如您所见,该索引未被使用。该表包含 525 行,上述查询返回 195 行。该表是一个物化视图,但这应该没有任何区别,我还有其他可以正常工作的索引。关于为什么我的索引没有在上述查询中使用的任何想法?
我改用基于多维数据集的方法来利用索引:
CREATE INDEX aggregate_cube ON aggregate USING gist (ll_to_earth(latitude, longitude));
explain analyze select name from aggregate where earth_box(ll_to_earth(53.574753, -2.1), 100 * 1609.344) @> ll_to_earth(latitude, longitude);
Bitmap Heap Scan on aggregate (cost=9.06..259.53 rows=69 width=516) (actual time=0.218..0.476 rows=134 loops=1)
Recheck Cond: ('(3779643.6387679, -143776.582140441, 5127079.5615671),(3789643.63851185, -133776.582396498, 5137079.56131104)'::cube @> (ll_to_earth(latitude, longitude))::cube)
-> Bitmap Index Scan on aggregate_cube (cost=0.00..9.05 rows=69 width=0) (actual time=0.190..0.190 rows=134 loops=1)
Index Cond: ('(3779643.6387679, -143776.582140441, 5127079.5615671),(3789643.63851185, -133776.582396498, 5137079.56131104)'::cube @> (ll_to_earth(latitude, longitude))::cube)
Total runtime: 0.516 ms
(5 rows)
Run Code Online (Sandbox Code Playgroud)