我有一個基於RubyOnRails 4.0的應用程序。我有兩個模型:商店和產品。如果我不正確地使用索引,系統中大約有150萬個產品會使其非常慢。在RubyOnRails中爲內部連接創建表的postgres索引
一些基本信息
- 商店的has_many產品
- Store.affiliate_type_id使用其中1 =附屬2 =不附屬
- 產品有像 「category_connection_id」(整數)和「is_available屬性「(布爾值)
In Feeded產品型號:
scope :affiliated, -> { joins(:store).where("stores.affiliate_type_id = 1") }
此查詢需要500ms左右,基本上中斷的網站:
FeededProduct.where(:is_available => true).affiliated.where(:category_connection_id => @feeded_product.category_connection_id)
對應的PostgreSQL:
FeededProduct Load (481.4ms) SELECT "feeded_products".* FROM "feeded_products" INNER JOIN "stores" ON "stores"."id" = "feeded_products"."store_id" WHERE "feeded_products"."is_available" = 't' AND "feeded_products"."category_connection_id" = 345 AND (stores.affiliate_type_id = 1)
更新。 PostgreSQL的EXPLAIN:
QUERY PLAN
-------------------------------------------------------------------------------------------------
Hash Join (cost=477.63..49176.17 rows=21240 width=1084)
Hash Cond: (feeded_products.store_id = stores.id)
-> Bitmap Heap Scan on feeded_products (cost=377.17..48983.06 rows=38580 width=1084)
Recheck Cond: (category_connection_id = 5923)
Filter: is_available
-> Bitmap Index Scan on cc_w_store_index_on_fp (cost=0.00..375.25 rows=38580 width=0)
Index Cond: ((category_connection_id = 5923) AND (is_available = true))
-> Hash (cost=98.87..98.87 rows=452 width=4)
-> Seq Scan on stores (cost=0.00..98.87 rows=452 width=4)
Filter: (affiliate_type_id = 1)
(10 rows)
問:如何創建,將採取內的索引聯接起來考慮,使這個更快?
'EXPLAIN ANALYZE'返回更多有用的細節。 –
謝謝,但我找不到在RubyOnRails中做這件事的好方法。有什麼建議嗎? – Christoffer
在PostgreSQL中,使用'explain analyze'而不是'explain'。 –