也比较一下PG中的like查询: like '%<str>%'

这里只是做一个简单的实验,似乎不能完全证明position()函数比like查询要快。

SELECT generate_series(1,10) as id, substr('abcdefghijklmnopqrstuvwxyz',1, (random()*26)::integer) as col2 into t1;

explain analyze select count(*) from t1 where col2 like '%bc%'
--------------------------------------------------------------------------------
----------------------------------
Aggregate (cost=20821.67..20821.68 rows=1 width=0) (actual time=407.894..407.8
94 rows=1 loops=1)
-> Seq Scan on t1 (cost=0.00..18563.00 rows=903467 width=0) (actual time=0.
105..320.662 rows=903565 loops=1)
Filter: (col2 ~~ '%bc%'::text)
Rows Removed by Filter: 96435
Total runtime: 408.081 ms
(5 rows)

iihero=# explain analyze select count(*) from t1 where position('bc' in col2)>0;
--------------------------------------------------------------------------------
----------------------------------
Aggregate (cost=21896.33..21896.34 rows=1 width=0) (actual time=714.827..714.8
27 rows=1 loops=1)
-> Seq Scan on t1 (cost=0.00..21063.00 rows=333333 width=0) (actual time=0.
140..629.252 rows=903565 loops=1)
Filter: ("position"(col2, 'bc'::text) > 0)
Rows Removed by Filter: 96435
Total runtime: 714.944 ms
(5 rows)

iihero=# create index idx_pos_bc_t1 on t1(position('bc' in col2));
--------------------------------------------------------------------------------
-------------------------------------------------------------
Aggregate (cost=18141.01..18141.02 rows=1 width=0) (actual time=388.336..388.3
36 rows=1 loops=1)
-> Bitmap Heap Scan on t1 (cost=6244.68..17307.68 rows=333333 width=0) (act
ual time=197.816..310.730 rows=903565 loops=1)
Recheck Cond: ("position"(col2, 'bc'::text) > 0)
-> Bitmap Index Scan on idx_pos_bc_t1 (cost=0.00..6161.35 rows=333333
width=0) (actual time=196.172..196.172 rows=903565 loops=1)
Index Cond: ("position"(col2, 'bc'::text) > 0)
Total runtime: 388.639 ms
(6 rows)


只有要函数索引完全能用上的情况下,才算有效。 当position位于左侧表达式时,并且含有动态变量,索引就无法用上了。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值