首页 > 解决方案 > 我想搜索2个字符,有什么解决办法吗?(三元组索引仅适用于至少 3 个字符)

问题描述

我在名字和姓氏列上有一个三元索引,我想搜索 2 个字符。我尝试在打开或关闭顺序扫描的情况下执行查询,并测量每种情况下需要多长时间,但两者都需要很多时间。有没有让我的 2 个字符搜索工作更快的解决方案?

在架构中我有:

t.index "(((((first_name)::text || ' '::text) || (last_name)::text)) gin_trgm_ops",名称:"index_users_full_name",使用::gin

标签: ruby-on-railspostgresqlperformance

解决方案


我不认为有任何内置的东西可以做到这一点。您可以创建一个函数,将文本转换为二元数组(决定如何处理空格、标点符号、非 ASCII 等),然后对该数组进行索引并使用&&运算符进行查询。但是,除非您的两个字符类似于“qz”,否则您可能无法获得足够的选择性来使索引变得有价值。

create function bigram(text) returns text[] language sql as $$
    select array_agg(substring($1,x,2)) from generate_series(1,length($1)-1) f(x);
$$ immutable;

create index on foobar using gin (bigram(t));
select * from foobar where bigram(t) && bigram('aa');

推荐阅读