如何让PostgreSQL使用gin_trgm_ops索引进行相等比较

use*_*780 4 postgresql postgresql-performance pg-trgm

有一个表和一个gin索引,插入1,000,000个随机数。0 < 数量 < 100,000。
测试两个等效查询

create table Test
(
    id   serial primary key,
    code varchar(255) not null
);
create index Test_code_gin on Test using gin (code gin_trgm_ops);

-- Test1
explain analyse
select * from Test where code like '1234';

-- Test2
explain analyse 
select * from Test where code = '1234';
Run Code Online (Sandbox Code Playgroud)

测试1使用gin_trgm_ops索引,执行时间:1.640 ms;
Test2不使用索引,执行时间:24.531 ms;

我该怎么做才能让 PostgreSQL 使用索引?或者修改ORM策略和我的SQL语句?或者干脆添加一个BTree索引?

jja*_*nes 5

v14 中添加了该功能。因此,您可以将 PostgreSQL 升级到 v14,然后将 pg_trgm 升级到最新版本(使用 pg_upgrade 升级不会自动执行此操作)。

但我只会创建 btree 索引,因为对于相等性来说,这应该比使用三元组更快。仅仅为了获得较差的实现而进行升级并不是一种胜利,除非索引所需的额外空间是无法忍受的。