我正在优化存储来自日志文件的信息的 Postgres 表。
这是查询:
SELECT c_ip as ip
, x_ctx as file_name
, date_time
, live
, c_user_agent as user_agent
FROM events
WHERE x_event = 'play'
AND date = '2012-12-01'
AND username = 'testing'
x_event、日期和用户名上有 b 树索引。在这个表中,大约有 2500 万行。现在查询大约需要 20-25(更正,更像是 40)秒,并返回 143,000 行。
那个时间是预期的吗?由于索引,我会认为它会更快。也许是因为它必须通过大量的数据?
编辑:这是解释分析:
Bitmap Heap Scan on events (cost=251347.32..373829.74 rows=35190 width=56) (actual time=5768.409..6124.313 rows=143061 loops=1)
Recheck Cond: ((date = '2012-12-01'::date) AND (username = 'testing'::text) AND (x_event = 'play'::text))
-> BitmapAnd (cost=251347.32..251347.32 rows=35190 width=0) (actual time=5762.083..5762.083 rows=0 loops=1)
-> Bitmap Index Scan on index_events_fresh_date (cost=0.00..10247.04 rows=554137 width=0) (actual time=57.568..57.568 rows=572221 loops=1)
Index Cond: (date = '2012-12-01'::date)
-> Bitmap Index Scan on index_events_fresh_username (cost=0.00..116960.55 rows=6328206 width=0) (actual time=3184.053..3184.053 rows=6245831 loops=1)
Index Cond: (username = 'testing'::text)
-> Bitmap Index Scan on index_events_fresh_x_event (cost=0.00..124112.84 rows=6328206 width=0) (actual time=2478.919..2478.919 rows=6245841 loops=1)
Index Cond: (x_event = 'play'::text)
Total runtime: 6148.313 ms
我对此有几个问题:
- 我对日期索引中有 554137 行是否正确?那里应该有少于 50 个日期。
- 我怎么知道它正在使用列出的三个索引?
- 列出的总运行时间约为 6 秒,但当我运行不带 EXPLAIN ANALYZE 的查询时,大约需要 40 秒。