将 gin_trgm_ops 的 2 个 GIN 索引合并为一个 | Postgres

Combine 2 GIN indexes with gin_trgm_ops into one | Postgres

我有一个流动的table

 create table mytable
(
id       serial     not null primary key,
text_id                      varchar(20)              not null,
customer_unit_id              text,
)

text_idcustomer_unit_id 基本上存储代码,例如 K-2021-8524 和类似代码。

在 Web 界面中,我使用搜索 window 按 text_idcustomer_unit_id 筛选条目。

典型的搜索是这样的

SELECT id, text_id
FROM mytable
WHERE UPPER(text_id::text) LIKE UPPER('%2021-8%')
OR UPPER(customer_unit_id ::text) LIKE UPPER('%176%')

我已经创建了 GIN 索引以方便搜索

CREATE INDEX IF NOT EXISTS trgrm_test_text ON mytable
USING gin (Upper(text_id) gin_trgm_ops);

CREATE INDEX IF NOT EXISTS trgrm_test_customer ON mytable
USING gin (Upper(customer_unit_id ) gin_trgm_ops);

我尝试制作 2 列 GIN 索引,以便有一个组合索引而不是 2 个单独的索引 - 但它不起作用(seq 扫描)

问题 – 对于这种类型的查询,是否可以使用一个组合索引而不是两个单独的索引???

谢谢....

PostgreSQL 版本 -11

另一种方法是创建第三列,其中包含一个 tsvector 和两列的内容,然后对其进行索引,例如:

ALTER TABLE mytable ADD COLUMN ts tsvector;
UPDATE mytable SET ts =  to_tsvector('english',text_id||' '||customer_unit_id);

CREATE INDEX trgrm_ts_vec_idx2 ON mytable USING gin (ts);

你可以这样查询:

SELECT id, text_id
FROM mytable
WHERE 
 ts @@ to_tsquery('english', 'k-2021-8 | 176')

如果你负担不起额外的列,你可以只在索引中使用 tsvector,但这会使查询有点混乱,而且速度应该也会慢一点:

CREATE INDEX IF NOT EXISTS trgrm_ts_vec_idx ON mytable 
USING gin (to_tsvector('english', text_id || ' ' || customer_unit_id));

然后这样查询:

SELECT id, text_id
FROM mytable
WHERE 
 to_tsvector('english', text_id || ' ' || customer_unit_id) @@ 
 to_tsquery('english', 'k-2021-8 | 176');

演示:db<>fiddle