我对查看 EXPLAIN ANALYZE 结果不是很熟悉,我的查询太慢了。我试图阅读如何解释解释查询的结果,但我仍然不知道我应该寻找什么,以及可能有什么问题。我有一种感觉,某处有一些大红灯在闪烁,我只是没看到。
所以查询很简单,看起来像这样:
EXPLAIN ANALYZE SELECT "cars".* FROM "cars" WHERE "cars"."sales_state" = 'onsale' AND "cars"."brand" = 'BMW' AND "cars"."model_name" = '318i' AND "cars"."has_auto_gear" = TRUE LIMIT 25 OFFSET 0
结果是这样的:
Limit (cost=0.00..161.07 rows=25 width=1245) (actual time=35.232..38.694 rows=25 loops=1)
-> Index Scan using index_cars_onsale_on_brand_and_model_name on cars (cost=0.00..1179.06 rows=183 width=1245) (actual time=35.228..38.652 rows=25 loops=1)
Index Cond: (((brand)::text = 'BMW'::text) AND ((model_name)::text = '318i'::text))
Filter: has_auto_gear"
Total runtime: 38.845 ms
一点背景知识:我在 Postgresql 9.1.6 上,在 Herokus 专用数据库上运行。我的数据库有大约 7,5Gb 的 RAM,表 cars 包含 3,1M 行,大约 2,0M 的行有 sales_state = 'onsale'。该表有 170 列。它使用的索引如下所示:
CREATE INDEX index_cars_onsale_on_brand_and_model_name
ON cars
USING btree
(brand COLLATE pg_catalog."default" , model_name COLLATE pg_catalog."default" )
WHERE sales_state::text = 'onsale'::text;
有人看到一些明显的大问题吗?
编辑:
SELECT pg_relation_size('cars'), pg_total_relation_size('cars');
pg_relation_size: 2058444800 pg_total_relation_size: 4900126720
SELECT pg_relation_size('index_cars_onsale_on_brand_and_model_name');
pg_relation_size: 46301184
SELECT avg(pg_column_size(cars)) FROM cars limit 5000;
平均:636.9732567210792995
没有限制:
EXPLAIN ANALYZE SELECT "cars".* FROM "cars" WHERE "cars"."sales_state" = 'onsale' AND "cars"."brand" = 'BMW' AND "cars"."model_name" = '318i' AND "cars"."has_auto_gear" = TRUE
Bitmap Heap Scan on cars (cost=12.54..1156.95 rows=183 width=4) (actual time=17.067..55.198 rows=2096 loops=1)
Recheck Cond: (((brand)::text = 'BMW'::text) AND ((model_name)::text = '318i'::text) AND ((sales_state)::text = 'onsale'::text))
Filter: has_auto_gear
-> Bitmap Index Scan on index_cars_onsale_on_brand_and_model_name (cost=0.00..12.54 rows=585 width=0) (actual time=15.211..15.211 rows=7411 loops=1)"
Index Cond: (((brand)::text = 'BMW'::text) AND ((model_name)::text = '318i'::text))
Total runtime: 56.851 ms