在 PostgreSQL 中當查詢使用 Index,我們目前看到了兩種方式:Index Scan 和 Bitmap Scan。 接下來就分別來看看他們各自的特性,以及適用的情境。
Index Scan 搜尋時,主要會有兩個步驟:
什麼時候會用到?
WHERE id = 123
)比如先前我們從 users table 內只用 id
查詢一筆特定的資料,使用的就是 Index Scan。
而 Bitmap scan 的運作方式為:
有看到差異了嗎?相較於 Index Scan 每次找到 row 的位置就會回到 Heap 找實際的資料,Bitamp 是找到多筆 row 的位置後,一次性的回去找實際的資料。這樣的方式可以比 Index Scan 減少來回在 Heap 找資料的次數。
什麼時候會用到?
WHERE status = 'active'
,但 active 佔了一半的資料)。WHERE email LIKE '%example.com' AND created_at > '2024-01-01'
。比如上一篇我們從 quizzes
中搜尋的條件分別落在不同的欄位,PostgreSQL 的 Planner 就認為 Bitmap Scan 比 Index scan 還要適合。
仔細看這張圖,也可以看到這兩個步驟:
Index Scan vs. Bitmap Scan 差異比較
特性 | Index Scan | Bitmap Scan |
---|---|---|
適用情境 | 查詢範圍較小 | 查詢範圍較大 |
存取方式 | 逐筆讀取 Index 和 Table | 先從 Index 批次找到資料,然後批次讀取 Table |
效率 | 適合小範圍查詢 | 適合大範圍篩選 |
回表(Heap Fetch) | 每筆都回表一次 | 批量回表,降低 I/O |
https://www.postgresql.org/docs/current/indexes-bitmap-scans.html