![](/img/trans.png)
[英]Efficient PostgreSQL query on timestamp using index or bitmap index scan?
[英]How to construct an efficient PostgreSQL index for a conditional date query?
我正在嘗試查詢約 1000 萬行的大型數據庫,以查找時間戳高於某個日期且 boolean 標志設置為 false 的所有行,例如:
SELECT COUNT(id) FROM mytable WHERE (NOT fresh OR created IS NULL OR created <= '2021-1-1');
這個查詢需要一個小時才能運行,但並不太復雜,所以我嘗試為它創建一個索引,例如:
CREATE INDEX CONCURRENTLY mytable_fresh_created ON mytable (fresh, created ASC) WHERE fresh = false;
但這對性能幾乎沒有任何改善。 運行EXPLAIN
顯示順序掃描:
Finalize Aggregate (cost=18641642.51..18641642.52 rows=1 width=8)
-> Gather (cost=18641642.29..18641642.50 rows=2 width=8)
Workers Planned: 2
-> Partial Aggregate (cost=18640642.29..18640642.30 rows=1 width=8)
-> Parallel Seq Scan on mytable (cost=0.00..18629381.98 rows=4504126 width=4)
Filter: ((NOT fresh) OR (created IS NULL) OR (created <= '2021-1-1'::timestamp with time zone))
所以看起來甚至沒有使用索引。
如何為此類查詢構建更好的索引?
當您使用OR
時,索引不使用。 我建議使用UNION ALL
。 例子:
SELECT *
FROM mytable
WHERE (created <= '2021-01-01'::date)
union all
SELECT *
FROM mytable
WHERE (created IS NULL)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.