位圖掃描是 PostgreSQL 针對「單表多索引 OR 條件」或「低選擇率索引」優化器的一種混合策略:
優勢:將隨機 I/O 轉為順序 I/O,減少頁面重複讀取;支持多索引 BITMAP OR/AND 合併。
QUERY PLAN
-----------------------------------------------------------------------
Bitmap Heap Scan on bitmap_test (cost=2023.16..4157.75 rows=99967 width=4)
(actual time=24.373..41.054 rows=100000 loops=1)
Recheck Cond: (is_visible = 'yes'::bpchar)
-> Bitmap Index Scan on idx_bitmap_is_visible (cost=0.00..1998.17 rows=99967 width=0)
(actual time=24.252..24.252 rows=100000 loops=1)
Index Cond: (is_visible = 'yes'::bpchar)
Total runtime: 47.175 ms
Recheck Cond:堆掃描階段需重新驗證的條件(因位圖可能無損壓縮導致誤判)。Bitmap Index Scan:索引層面生成位圖,rows=100000 為估算命中行數。loops=1:單次執行(非參數化循環)。Total runtime:含客戶端傳輸的實際耗時。| 場景 | 是否觸發位圖掃描 | 理由 |
|---|---|---|
| 單索引、高選擇率(<1-5%) | 否 | 直接 Index Scan 更優 |
| 單索引、低選擇率(>10-20%) | 是 | 位圖轉順序 I/O 划算 |
| 多索引 OR 條件 | 是 | BitmapOr 合併位圖 |
| 多索引 AND 條件 | 是 | BitmapAnd 交集位圖 |
| LIMIT 小結果集 | 通常否 | 優化器傾向 Index Scan + Limit |
shared_buffers、work_mem:位圖構建佔用工作記憶體,過大導致磁盤臨時文件。random_page_cost、seq_page_cost 引導優化器選擇。ANALYZE),否則行數估算偏差導致錯誤選擇。