postgresql - GIST 索引未在带有 LIKE 的 SELECT 语句中使用

标签 postgresql postgresql-8.3

在 PostgreSQL 8.3 中(抱歉版本过时 - 我无法更改)我有一个这样的表:

CREATE TABLE tablephonebook
(
  id bigserial NOT NULL,
  name1 text,
  name2 text,
  number text,
  ...
  CONSTRAINT tablephonebook_pkey PRIMARY KEY (id)
)

table 上有大约。 50 000 条记录。

我已成功创建 GIST 索引:

CREATE INDEX trgm_idx ON tablephonebook USING gist (name1 gist_trgm_ops, name2 gist_trgm_ops);

使用 LIKE(或 ILIKE)运算符进行文本搜索花费的时间太长并且不使用 GIST 索引:

EXPLAIN ANALYZE SELECT id, name1, name2
  WHERE name1 ILIKE '%south%'
     OR name2 ILIKE '%south%'
   FROM tablephonebook
  ORDER BY id
  LIMIT 1000;

Limit  (cost=0.00..10737.05 rows=903 width=80) (actual time=333.125..333.125 rows=0 loops=1)
  ->  Seq Scan on tablephonebook  (cost=0.00..10737.05 rows=903 width=80) (actual time=333.123..333.123 rows=0 loops=1)"
      Filter: ((name1 ~~* '%south%'::text) OR (name2 ~~* '%south%'::text))
Total runtime: 333.155 ms

我做错了什么?我读过 LIKE/ILIKE 使用这个词索引。

作为替代方法,我尝试使用“to_tsquery”进行全文搜索(并获得惊人的速度),但我无法找到所需的子字符串匹配项。全文搜索只能找到完整的单词是正确的吗?

最佳答案

问题是你的版本太旧了。
这与现代 PostgreSQL 的预期一样有效:

SQL Fiddle demo for pg 9.3.

但在 pg 8.3 中没有:

SQL Fiddle demo for pg 8.3.

Postgres 9.1 添加了对此的支持。 Per release notes :

E.28.3.13.2. Performance

Add support for `LIKE` and `ILIKE` index searches to `contrib/pg_trgm` (Alexander Korotkov)

关于postgresql - GIST 索引未在带有 LIKE 的 SELECT 语句中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24553730/

相关文章:

sql - 查询返回确切的行数

SQL:选择所有连接记录都满足某些条件的记录

连续两个日期的 SQL 窗口聚合

sql - 在 golang 中处理插入到具有不同和大量列的数据库

sql - 这两个 PostgreSQL 函数是否等价? (返回表和返回集)

postgresql - 如何从 pl/pgsql 函数中调用 shell 命令?

ruby - 从 Postgres 时间戳中添加或减去时间

sql - 如何在 postgres 数据库上切换两个 ID [PK]?

用于 UNION 大量表的 SQL 脚本

sql - 如何每天选择超过1条记录?