[英]Optimize select query along with where clause to use index scan in postgres
我有一個表“ offer_facts”,其中有許多列,包括product_dimension_id(產品尺寸表的外鍵)和source_name(varchar)。 這兩個列都已索引。 目前,此表中大約有12萬行。 該表在不斷增長(每天約2萬)。
下面是查詢和我得到的輸出。
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);
我已經抽真空並分析了桌子。
這是您的查詢:
SELECT DISTINCT product_dimension_id
FROM offer_facts
WHERE source_name = 'customer_conti' ;
最佳索引是復合索引: offer_facts(source_name, product_dimension_id)
。 每列上的單個索引沒有那么有用。 該查詢可以利用索引掃描。 Postgres 應該足夠聰明才能找到該執行路徑。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.