如何修复“项目”的顺序扫描?我已经有[league_id,buyout_amount]
的索引"Limit (cost=72399.08..72399.15 rows=25 width=553) (actual time=2037.893..2037.898 rows=25 loops=1)"
" -> Sort (cost=72399.08..72817.16 rows=167231 width=553) (actual time=2037.891..2037.894 rows=25 loops=1)"
" Sort Key: normalized_buyout, id"
" Sort Method: top-N heapsort Memory: 41kB"
" -> Seq Scan on items (cost=0.00..67679.95 rows=167231 width=553) (actual time=0.764..1906.766 rows=183374 loops=1)"
" Filter: ((buyout_amount <> 0::numeric) AND (league_id = 1))"
"Total runtime: 2037.949 ms"
这是查询
SELECT "items".* FROM "items"
WHERE (items.league_id = '1') AND (buyout_amount <> 0)
ORDER BY normalized_buyout ASC, items.id DESC
LIMIT 25
当前索引(与此查询相关)
-- Index: index_items_on_buyout_amount
-- DROP INDEX index_items_on_buyout_amount;
CREATE INDEX index_items_on_buyout_amount
ON items
USING btree
(buyout_amount);
-- Index: index_items_on_id
-- DROP INDEX index_items_on_id;
CREATE INDEX index_items_on_id
ON items
USING btree
(id DESC);
-- Index: index_items_on_id_and_league_id
-- DROP INDEX index_items_on_id_and_league_id;
CREATE INDEX index_items_on_id_and_league_id
ON items
USING btree
(id, league_id);
-- Index: index_items_on_id_and_normalized_buyout
-- DROP INDEX index_items_on_id_and_normalized_buyout;
CREATE INDEX index_items_on_id_and_normalized_buyout
ON items
USING btree
(id DESC, normalized_buyout);
-- Index: index_items_on_league_id
-- DROP INDEX index_items_on_league_id;
CREATE INDEX index_items_on_league_id
ON items
USING btree
(league_id);
-- Index: index_items_on_league_id_and_buyout_amount
-- DROP INDEX index_items_on_league_id_and_buyout_amount;
CREATE INDEX index_items_on_league_id_and_buyout_amount
ON items
USING btree
(league_id, buyout_amount);
-- Index: index_items_on_league_id_and_id
-- DROP INDEX index_items_on_league_id_and_id;
CREATE INDEX index_items_on_league_id_and_id
ON items
USING btree
(league_id, id DESC);
-- Index: index_items_on_normalized_buyout
-- DROP INDEX index_items_on_normalized_buyout;
CREATE INDEX index_items_on_normalized_buyout
ON items
USING btree
(normalized_buyout);
答案 0 :(得分:0)
我发现我的ORDER BY
索引没有被使用。通过添加部分索引WHERE buyout_amount <> 0 ORDER BY normalized_buyout, id DESC
,它开始使用索引。
答案 1 :(得分:0)
对于强制类型转换,Postgres可能特别敏感/愚蠢:如果你不使用与列相同类型的常量,它(通常根据我的经验)将列强制转换为常量,从而使索引无效。
确保常量与列类型一致。
更改
WHERE items.league_id = '1' -- constant is text
AND buyout_amount <> 0 -- constant is int
要:
WHERE items.league_id = 1 -- constant is int
AND buyout_amount <> 0.0 -- constant is decimal