标签
PostgreSQL , bitmap index scan , bitmap heap scan
背景
在PostgreSQL中,多个单列索引是可以用在组合查询SQL中的,也就是说实现了bitmap scan。
比如
select * from tbl where c1=1 and c2=1 or c3=1;
用到了3列,如果这3列分别有一个索引,那么PostgreSQL会使用这三个索引的bitmap scan。
PostgreSQL是如何处理多个组合条件的BITMAP SCAN的呢?
Bitmap Heap Scan on customers (cost=25.76..61.62 rows=10 width=13) (actual time=0.077..0.077 rows=2 loops=1)
Recheck Cond: (((username)::text < 'user100'::text) AND (customerid < 1000))
-> BitmapAnd (cost=25.76..25.76 rows=10 width=0) (actual time=0.073..0.073 rows=0 loops=1)
-> Bitmap Index Scan on ix_cust_username (cost=0.00..5.75 rows=200 width=0) (actual time=0.006..0.006 rows=2 loops=1)
Index Cond: ((username)::text < 'user100'::text)
-> Bitmap Index Scan on customers_pkey (cost=0.00..19.75 rows=1000 width=0) (actual time=0.065..0.065 rows=999 loops=1)
Index Cond: (customerid < 1000)
bitmap scan原理
对于每个查询条件,在对应索引中找到符合条件的堆表PAGE,每个索引构造一个bitmap串。
在这个bitmap串中,每一个BIT位对应一个HEAP PAGE,代表这个HEAP PAGE中有符合该条件的行。
根据条件的多少,组成了多个bitmap。
例如 a=1 or a=2 是两个bitmap。