这篇文章主要介绍了PostgreSQL模糊匹配走索引的操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧。
场景 lower(name) like 'pf%'
create table users (id int primary key, name varchar(255));
Create or replace function random_string(length integer) returns text as
$$
declare
chars text[] := '{0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}';
result text := '';
i integer := 0;
begin
if length < 0 then
raise exception 'Given length cannot be less than 0';
end if;
for i in 1..length loop
result := result || chars[1+random()*(array_length(chars, 1)-1)];
end loop;
return result;
end;
$$ language plpgsql;
insert into users values(generate_series(1,50000), random_string(15));
普通bt:不走索引
pg_trgm模块提供函数和操作符测定字母数字文本基于三元模型匹配的相似性,还有支持快速搜索相似字符串的索引操作符类。三元模型是一组从一个字符串中获得的三个连续的字符。我们可以通过计数两个字符串共享的三元模型的数量来测量它们的相似性。这个简单的想法证明在测量许多自然语言词汇的相似性时是非常有效的。
1CREATE INDEX users_idx0 ON users (name);
全字匹配查询(走索引)
explain select * from users where name='pfDNQVmhqDrF1EY';
QUERY PLAN
-------------------------------------------------------------------------
Index Scan using users_idx0 on users (cost=0.29..8.31 rows=1 width=20)
Index Cond: ((name)::text = 'pfDNQVmhqDrF1EY'::text)
(2 rows)
加函数全字匹配(不走索引)
explain select * from users where lower(name)='pfDNQVmhqDrF1EY';
QUERY PLAN
-----------------------------------------------------------
Seq Scan on users (cost=0.00..1069.00 rows=250 width=20)
Filter: (lower((name)::text) = 'pfDNQVmhqDrF1EY'::text)
(2 rows)
模糊匹配(不走索引)
explain select * from users where name like 'pf%';
QUERY PLAN
--------------------------------------------------------
Seq Scan on users (cost=0.00..944.00 rows=5 width=20)
Filter: ((name)::text ~~ 'pf%'::text)
explain select * from users where name like 'pf_';
QUERY PLAN
--------------------------------------------------------
Seq Scan on users (cost=0.00..944.00 rows=5 width=20)
Filter: ((name)::text ~~ 'pf_'::text)
字段带函数的bt索引:函数走索引
drop index users_idx0;CREATE INDEX users_dex1 ON users (lower(name));
加函数全字匹配(走索引)