低限制LIMIT /高OFFSET的成本非常高

时间:2011-01-18 22:16:42

标签: sql performance postgresql explain

我的产品桌很大。我需要以非常高的偏移量选择几种产品(例如下面的例子)。关于索引和性能的Postgresql手册建议在ORDER BY +最终条件使用的列上创建索引。一切都是桃子,没有使用。但对于高偏移值,LIMIT非常昂贵。任何人都知道可能是什么原因?

以下查询可以运行几分钟。

Indexes:
"product_slugs_pkey" PRIMARY KEY, btree (id)
"index_for_listing_by_default_active" btree (priority DESC, name, active)
"index_for_listing_by_name_active" btree (name, active)
"index_for_listing_by_price_active" btree (master_price, active)
"product_slugs_product_id" btree (product_id)

EXPLAIN SELECT * FROM "product_slugs" WHERE ("product_slugs"."active" = 1) ORDER BY product_slugs.name ASC LIMIT 10 OFFSET 14859;
                                                       QUERY PLAN                                                        
-------------------------------------------------------------------------------------------------------------------------
 Limit  (cost=26571.55..26589.43 rows=10 width=1433)
   ->  Index Scan using index_for_listing_by_name_active on product_slugs  (cost=0.00..290770.61 rows=162601 width=1433)
         Index Cond: (active = 1)
(3 rows)

1 个答案:

答案 0 :(得分:5)

此处的index_for_listing_by_name_active索引不会有太大帮助,因为结果集中的产品不一定在索引中是连续的。尝试仅在那些活跃的产品上按名称创建条件索引:

CREATE INDEX index_for_listing_active_by_name
  ON product_slugs (name)
  WHERE product_slugs.active = 1;