以下是我的查询.我试图让它使用索引扫描,但它只会seq扫描.
顺便提一下,metric_data表有1.3亿行.度量表有大约2000行.
metric_data表列:
metric_id integer,t timestamp,d double precision,PRIMARY KEY (metric_id,t)
SELECT S.metric,D.t,D.d FROM metric_data D INNER JOIN metrics S ON S.id = D.metric_id WHERE S.NAME = ANY (ARRAY ['cpu','mem']) AND D.t BETWEEN '2012-02-05 00:00:00'::TIMESTAMP AND '2012-05-05 00:00:00'::TIMESTAMP;
说明:
Hash Join (cost=271.30..3866384.25 rows=294973 width=25) Hash Cond: (d.metric_id = s.id) -> Seq Scan on metric_data d (cost=0.00..3753150.28 rows=29336784 width=20) Filter: ((t >= '2012-02-05 00:00:00'::timestamp without time zone) AND (t <= '2012-05-05 00:00:00'::timestamp without time zone)) -> Hash (cost=270.44..270.44 rows=68 width=13) -> Seq Scan on metrics s (cost=0.00..270.44 rows=68 width=13) Filter: ((sym)::text = ANY ('{cpu,mem}'::text[]))
为了测试目的,您可以通过在当前会话中“禁用”顺序扫描强制使用索引:
SET enable_seqscan = OFF;
Details in the manual here.我引用“禁用”,因为实际上不能禁用顺序表扫描.但是Postgres现在可以选择任何其他可用选项.这将证明可以使用(metric_id,t)上的多列索引 – 不如在引导列上的索引那么有效.
如果将PRIMARY KEY中的顺序切换为(t,metric_id),则可能会获得更好的结果(不创建更多索引).
> Is a composite index also good for queries on the first field?
请注意,您通常不需要通过手动干预强制更好的查询计划.如果设置enable_seqscan = OFF导致更好的计划,有可能在您的安装过程中出现.考虑这个相关答案: