【发布时间】:2020-04-23 18:54:46
【问题描述】:
我有一个带有时间戳字段的表。该表有数百万个来自几年的条目,我希望有一个按日期查询。
它没有按日期索引,所以我这样做了:
CREATE INDEX dt_crea_day_idx
ON my_table (date(dt_crea at TIME ZONE 'UTC'));
之后,下一个查询所用的时间与索引之前的时间相同:
SELECT dt_crea::date as dt_custom, field1, field2
FROM my_table
WHERE field1='some_value'
AND dt_crea::date = '2020-04-23'
ORDER BY dt_custom desc, field2
如何按日期提高此类查询的性能?
编辑:分析 pifor 询问:
Sort (cost=9616582.37..9616585.03 rows=1064 width=27) (actual time=290355.874..290355.906 rows=670 loops=1)
Sort Key: field2
Sort Method: quicksort Memory: 77kB
-> Seq Scan on my_table (cost=0.00..9616528.88 rows=1064 width=27) (actual time=72308.452..290355.232 rows=670 loops=1)
Filter: (((field1)::text = 'some_value'::text) AND ((dt_crea)::date = '2020-04-23'::date))
Rows Removed by Filter: 255195339
Planning time: 0.086 ms
Execution time: 290355.951 ms
【问题讨论】:
-
dt_crea 的确切数据类型是什么?你跑
ANALYZE my_table了吗?请发布EXPLAIN ANALYZE <your query>的输出 -
你的 where 条件必须使用 exactly 与索引相同的表达式,例如
and date(dt_crea at TIME ZONE 'UTC') = ... -
@a_horse_with_no_name 成功了!也许我误解了一些概念。我希望将字段索引为日期后,我如何使用日期并不重要。最初我试图索引 ((dt_crea::date)) 但它抛出一个错误说:错误:索引表达式中的函数必须标记为 IMMUTABLE。你认为这是最好的近似吗?按 (date(dt_crea at TIME ZONE 'UTC')) 索引并按 (date(dt_crea at TIME ZONE 'UTC')) 搜索?
标签: postgresql performance indexing