Rails / Postgresql查询很慢

时间:2015-05-05 16:28:09

标签: ruby-on-rails postgresql activerecord

我的查询导致我的Rails应用程序出现很多问题。对130万行运行的查询如下:

SELECT COUNT(*)
FROM "products"
INNER JOIN "categories" 
   ON "categories"."id" = "products"."category_id"
WHERE "products"."disabled" = 'f'
  AND (categories.is_adult = 't'
  AND merchant_image_url is NOT NULL
  AND advertiser_id in (1,3,8,9,12,16,17,18,24,27,31,32,34,40,44,47,48,53,55,57,61,64
              ,69,78,79,80,81,85,89,91,95,98,102,110,113,114,119,127,128,130,133,134))

查询的缓慢部分是:

advertiser_id in (1,3,8,9,12,16,17,18,24,27,31,32,34,40,44,47,48,53,55,57,61,64,
               69,78,79,80,81,85,89,91,95,98,102,110,113,114,119,127,128,130,133,134))

advertiser_id

上有一个索引

这是用户首选项,并且是可变的。如果没有这个,查询运行速度非常快。

如果我没有提供任何其他信息,请询问我,我会尽快添加。提前谢谢!

更新1 以下是查询计划:

Aggregate  (cost=198184.75..198184.76 rows=1 width=0) (actual time=11942.818..11942.818 rows=1 loops=1)
  ->  Hash Join  (cost=8065.09..197269.21 rows=366218 width=0) (actual time=110.651..11821.545 rows=349373 loops=1)
        Hash Cond: (products.category_id = categories.id)
        ->  Bitmap Heap Scan on products  (cost=8047.13..192215.75 rows=366218 width=4) (actual time=109.655..11470.039 rows=349373 loops=1)
              Recheck Cond: (advertiser_id = ANY ('{1,3,8,9,12,16,17,18,24,27,31,32,34,40,44,47,48,53,55,57,61,64,69,78,79,80,81,85,89,91,95,98,102,110,113,114,119,127,128,130,133,134}'::integer[]))
              Rows Removed by Index Recheck: 459153
              Filter: ((NOT disabled) AND (merchant_image_url IS NOT NULL))"
              Rows Removed by Filter: 112084
              ->  Bitmap Index Scan on index_products_on_advertiser_id  (cost=0.00..7955.57 rows=465290 width=0) (actual time=106.865..106.865 rows=461457 loops=1)
                    Index Cond: (advertiser_id = ANY ('{1,3,8,9,12,16,17,18,24,27,31,32,34,40,44,47,48,53,55,57,61,64,69,78,79,80,81,85,89,91,95,98,102,110,113,114,119,127,128,130,133,134}'::integer[]))
        ->  Hash  (cost=11.87..11.87 rows=487 width=4) (actual time=0.944..0.944 rows=487 loops=1)
              Buckets: 1024  Batches: 1  Memory Usage: 18kB
              ->  Seq Scan on categories  (cost=0.00..11.87 rows=487 width=4) (actual time=0.007..0.616 rows=487 loops=1)
Total runtime: 11943.149 ms

和解释

enter image description here

0 个答案:

没有答案