PostgreSQL数据库中如何保证LIKE语句的效率( 二 )


                                                      QUERY PLAN                                                       
———————————————————————————————————————–
Seq Scan on testliketb01  (cost=0.00..11405.00 rows=125350 width=52) (actual time=0.014..177.571 rows=124952 loops=1)
   Filter: ((username)::text ~~ ‘王%’::text)
   Rows Removed by Filter: 375048
Planning Time: 0.121 ms
Execution Time: 190.554 ms
(5 rows)
 
结论:LIKE查询没有走索引 创建普通索引: testdb01=# create index idx_testliketb01_username on testliketb01(username); CREATE INDEX 执行三遍:analyze testliketb01 ; 重新执行LIKE语句 , 发现还是没有走索引 创建包含operator class的索引: testdb01=# create index idx_testliketb01_username on testliketb01(username varchar_pattern_ops); CREATE INDEX 执行三遍:analyze testliketb01 ;
testdb01=# explain analyze select * from testliketb01 where username like ‘王%’;
                                                                   QUERY PLAN                                                                    
————————————————————————————————————————————————-
Bitmap Heap Scan on testliketb01  (cost=2665.26..9387.14 rows=125350 width=52) (actual time=31.383..94.745 rows=124952 loops=1)
   Filter: ((username)::text ~~ ‘王%’::text)
   Heap Blocks: exact=5155
   ->  Bitmap Index Scan on idx_testliketb01_username  (cost=0.00..2633.92 rows=125350 width=0) (actual time=29.730..29.730 rows=124952 loops=1)
         Index Cond: (((username)::text ~>=~ ‘王’::text) AND ((username)::text ~<~ ‘玌’::text))
Planning Time: 0.111 ms
Execution Time: 107.030 ms
(7 rows)
 
结论:在创建完普通索引并收集统计信息后数据库在执行LIKE语句时有可能仍然无法使用索引 。在创建完带有操作类的索引收集完统计信息后 , 执行LIKE语句可以看到正常使用索引 , 且执行效率有了不小提升 。
PS:operator class是Postgresql新版中创建索引的新选项 , 旨在通过制定索引的操作类可以更精准的收集统计信息 。