我使用Rails和Postgresql并且有一个非常大的表(1.3M项)称为FeededProducts
我在Rails中使用此调用:
@feed_products = FeededProduct.where("category_connection_id IN (?) AND is_available = ?", @page.category_connections.pluck(:id), true)
导致以下SQL调用:
FeededProduct Load (185.8ms) SELECT "feeded_products".* FROM "feeded_products" WHERE (category_connection_id IN (8,2579,3263,7791,7838) AND is_available = 't')
我的数据库中有一个索引:
add_index "feeded_products", ["category_connection_id", "is_available", "store_id"], name: "cc_w_store_index_on_fp", using: :btree
add_index "feeded_products", ["category_connection_id", "is_available"], name: "cc_index_on_fp", using: :btree
我希望这个SQL比通常的150-300毫秒快得多。这是正常的吗?我在这里遗漏了一些可以改进的东西吗?
编辑:SQL Explain输出(使用eyeballs gem):
@feed_products = FeededProduct.where("category_connection_id IN (?) AND is_available = ?", @page.category_connections.pluck(:id), true).eyeballs.explain
(1.9ms) SELECT "category_connections"."id" FROM "category_connections" WHERE "category_connections"."page_id" = $1 [["page_id", 162]]
FeededProduct Load (208.4ms) SELECT "feeded_products".* FROM "feeded_products" WHERE (category_connection_id IN (8,2579,3263,7791,7838) AND is_available = 't')
=> ["
Bitmap Heap Scan on public.feeded_products (cost=875.39..74405.02 rows=36805 width=1085) (actual time=12.821..44.605 rows=37314 loops=1)
Output: id, name, description, category, price, currency, in_stock, product_url, image_url, tracking_url, created_at, updated_at, store_id, slug, is_available, price_before, bad_image, category_connection_id
Recheck Cond: (feeded_products.category_connection_id = ANY ('{8,2579,3263,7791,7838}'::integer[]))
Filter: feeded_products.is_available
Heap Blocks: exact=9428
Buffers: shared hit=9545
-> Bitmap Index Scan on cc_index_on_fp (cost=0.00..866.19 rows=36805 width=0) (actual time=10.617..10.617 rows=37314 loops=1)
Index Cond: ((feeded_products.category_connection_id = ANY ('{8,2579,3263,7791,7838}'::integer[])) AND (feeded_products.is_available = true))
Buffers: shared hit=117
Planning time: 0.323 ms
Execution time: 47.059 ms
"]