我在 Postgres 9.4 工作。我有一个这样的表和索引:
Table "public.title"
Column | Type | Modifiers
---------------------------------+-------------------------+----------------------------------------------------
id | integer | not null default nextval('title_id_seq'::regclass)
pty_addr | character varying(1000) | not null
我在该pty_addr
列上有一个 GIN 索引:
"title_pty_add_15f367_gin" gin (pty_addr)
我的查询是这样的:
EXPLAIN ANALYZE SELECT * FROM "title" WHERE pty_addr LIKE '%FOO%';
此查询正在执行顺序扫描,耗时 1.2 秒:
QUERY PLAN
---------------------------------------------------------------------------------------------------------------
Seq Scan on title (cost=0.00..193271.60 rows=599 width=4446) (actual time=1.191..1220.640 rows=7945 loops=1)
Filter: ((pty_addr)::text ~~ '%FOO%'::text)
Rows Removed by Filter: 3592055
Planning time: 0.330 ms
Execution time: 1220.992 ms
为什么这个查询不使用索引?
如果你想为不是前缀查询的 LIKE 或 ILIKE 查询建立索引,那么你应该查看pg_trgm扩展,给出一个如下所示的索引:
此外,自 9.4 以来也有了实质性的改进。至少升级到 9.6 对您自己有好处。