优化选择查询以及where子句以在postgres中使用索引扫描

时间:2015-09-17 13:16:39

标签: sql postgresql

我有一个包含许多列的表“offer_facts”,包括product_dimension_id(产品维度表的外键)和source_name(varchar)。这两列都被编入索引。此刻大约有120K行。该表不断增长(每天约20K)。

以下是查询和我得到的输出。

SELECT version() "PostgreSQL 9.4.4 on x86_64-unknown-linux-gnu, compiled by gcc (Ubuntu 4.8.2-19ubuntu1) 4.8.2, 64-bit"

EXPLAIN (ANALYZE, BUFFERS) SELECT DISTINCT product_dimension_id from offer_facts WHERE source_name='customer_conti' 

输出

HashAggregate  (cost=36619.24..36621.37 rows=213 width=4) (actual time=2654.272..2655.064 rows=399 loops=1)
  Group Key: product_dimension_id
  Buffers: shared hit=2697 read=17687
  ->  Seq Scan on offer_facts  (cost=0.00..35425.82 rows=477367 width=4) (actual time=0.021..1525.361 rows=479880 loops=1)
        Filter: ((source_name)::text = 'customer_conti'::text)
        Rows Removed by Filter: 723466
        Buffers: shared hit=2697 read=17687
Planning time: 0.201 ms
Execution time: 2655.778 ms

我不确定为什么它正在进行Seq Scan而不是Index Scan。

我用

创建了索引
CREATE INDEX idx_offer_facts_dimensions ON offer_facts USING btree (source_name COLLATE pg_catalog."default", shop_dimension_id, time_dimension_id, date_dimension_id, source_dimension_id, product_dimension_id);

我已经假装并分析了表格。

1 个答案:

答案 0 :(得分:1)

这是您的查询:

SELECT DISTINCT product_dimension_id 
FROM offer_facts
WHERE source_name = 'customer_conti' ;

最佳索引是综合索引:offer_facts(source_name, product_dimension_id)。每列的各个索引都没有用。此查询可以使用索引扫描; Postgres 应该足够聪明才能找到执行路径。