私はRubyOnRails 4.0ベースのアプリを持っています。私は2つのモデルを持っています:店舗と商品。システムに約150万の製品があり、インデックスを適切に使用しないとかなり遅くなります。 1 =附属2が RubyOnRailsで内部結合テーブルを作成する
いくつかの基本的な情報
- ストアにhas_many製品
- Store.affiliate_type_idが使用されているが、 "category_connection_id"(整数)と「is_availableなどの属性を持っています"(ブール値)
In FeededProductモデル:
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'の代わりに' explain analyze'を使います。 –