1、帶前綴的模糊查詢 ~'^abc'
可以使用btree索引優化
create index idx_info on table_name(info)
2、帶后綴的模糊查詢 ~'abc$'
可以使用reverse函數btree索引
create index idx_info1 on table_name(reverse(info));
3、不帶前后綴的模糊查詢和正則表達式查詢
pg_trgm可以使用trgm的gin索引
CREATE EXTENSION pg_trgm; CREATEINDEX idx_info2 ontable_name using gin(info gin_trgm_ops);
重點說一下涉及到中文匹配的優化方法,因為trgm不支持wchar,因此需要轉換,本來相對TEXT(textsend(text))函數創建索引,但是報錯提醒函數必須是IMMUTABLE,因此手中創建一個
函數
create or replace function textsend_i (text) returns bytea as $$ select textsend($1); $$ language sql strict immutable;
然后再創建索引:
create index idx_name_1 on jd_daojia_product_1225 using gin(text(textsend_i(product_name)) gin_trgm_ops);
執行查詢,發現已經走索引了
SELECT * FROM jd_daojia_product_1225 where text(textsend_i(product_name)) ~ text(textsend_i('蘋果')) limit 10
Limit (cost=22.60..63.55 rows=10 width=295)
-> Bitmap Heap Scan on jd_daojia_product_1225 (cost=22.60..1398.39 rows=336 width=295)
Recheck Cond: ((textsend_i(product_name))::text ~ '\350\213\271\346\236\234'::text)
-> Bitmap Index Scan on idx_name_1 (cost=0.00..22.52 rows=336 width=0)
Index Cond: ((textsend_i(product_name))::text ~ '\350\213\271\346\236\234'::text)
