PostgreSQL正则及模糊查询优化

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)

  

  

转载于:https://www.cnblogs.com/guoxueyuan/p/8625458.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值