【问题标题】:My PostgreSQL 10 query is very slow, need a way to make it faster我的 PostgreSQL 10 查询很慢,需要一种方法让它更快
【发布时间】:2019-10-01 05:40:36
【问题描述】:

我使用的是 PostgreSQL 10

这是我的模型:
https://imgur.com/bibWSq8

每个review 只属于一个product。每个product 可以属于多个categorys。每个category 只能有一个父category。 我正在使用 Prisma 来查询数据库。这是一种ORM。 我想选择属于具有id = 27category 的所有products 中的前10 个reviews。

这是 Prisma 生成的查询:

select
"Alias"."id"
from "database"."review" as "Alias"
where ("Alias"."id"
       in (select "database"."review"."id"
           from "database"."review"
           where "database"."review"."product"
                 in (select "database"."category_to_product"."product"
                     from "database"."category_to_product"
                     join "database"."category" as "category_product_Alias"
                        on "category_product_Alias"."id" = "database"."category_to_product"."category"
                     where ("category_product_Alias"."id" = 27
                            or "category_product_Alias"."id"
                               in (select "database"."category"."id"
                                   from "database"."category"
                                   join "database"."category" as "category_category_product_Alias"
                                      on "category_category_product_Alias"."id" = "database"."category"."parent"
                                   where "category_category_product_Alias"."id" = 27
                                  )
                           )
                    )
          )
      )
order by "Alias"."id" desc
limit 11
offset 0;

有 1.500.000 reviews、12.000 products 和 130 categorys。该查询需要将近 3 秒才能完成。

我尝试创建索引,但没有成功:

CREATE UNIQUE INDEX category_pkey ON "database".category USING btree (id)
CREATE INDEX idx_category_parent ON "database".category USING btree (parent)
CREATE UNIQUE INDEX "category_to_product_AB_unique" ON "database".category_to_product USING btree (category, product)
CREATE INDEX "category_to_product_B" ON "database".category_to_product USING btree (product))
CREATE UNIQUE INDEX product_pkey ON "database".product USING btree (id)
CREATE INDEX idx_review_product ON "database".review USING btree (product)
CREATE UNIQUE INDEX review_pkey ON "database".review USING btree (id)

这是运行explain analyze时的结果:

Limit  (cost=9.00..101.89 rows=11 width=4) (actual time=3428.508..3431.048 rows=11 loops=1)
  ->  Merge Semi Join  (cost=9.00..12584725.82 rows=1490226 width=4) (actual time=3428.507..3431.043 rows=11 loops=1)
        Merge Cond: ("Alias".id = review.id)
        ->  Index Only Scan Backward using review_pkey on review "Alias"  (cost=0.43..84869.82 rows=1490226 width=4) (actual time=0.008..152.954 rows=1054436 loops=1)
              Heap Fetches: 0
        ->  Nested Loop Semi Join  (cost=8.57..12477502.61 rows=1490226 width=4) (actual time=3188.974..3191.303 rows=11 loops=1)
              ->  Index Scan Backward using review_pkey on review  (cost=0.43..266561.32 rows=1490226 width=8) (actual time=0.004..415.244 rows=1054436 loops=1)
              ->  Nested Loop  (cost=8.14..8.18 rows=1 width=4) (actual time=0.002..0.002 rows=0 loops=1054436)
                    ->  Index Scan using "category_to_product_B" on category_to_product  (cost=0.29..0.30 rows=1 width=8) (actual time=0.001..0.001 rows=1 loops=1054436)
                          Index Cond: (product = review.product)
                    ->  Index Only Scan using category_pkey on category "category_product_Alias"  (cost=7.86..7.88 rows=1 width=4) (actual time=0.001..0.001 rows=0 loops=1084175)
                          Index Cond: (id = category_to_product.category)
                          Filter: ((id = 27) OR (hashed SubPlan 1))
                          Rows Removed by Filter: 1
                          Heap Fetches: 0
                          SubPlan 1
                            ->  Nested Loop  (cost=0.00..7.71 rows=1 width=4) (actual time=0.016..0.016 rows=0 loops=1)
                                  ->  Seq Scan on category  (cost=0.00..3.85 rows=1 width=8) (actual time=0.015..0.016 rows=0 loops=1)
                                        Filter: (parent = 27)
                                        Rows Removed by Filter: 148
                                  ->  Seq Scan on category "category_category_product_Alias"  (cost=0.00..3.85 rows=1 width=4) (never executed)
                                        Filter: (id = 27)
Planning time: 0.649 ms
Execution time: 3431.098 ms

我觉得我的数据不是太大,但是查询太慢了。有什么办法让它更快?

更新 1 我只是按照@Laurenz Albe 的方式,它更快。这是结果

Limit  (cost=217773.56..217773.59 rows=11 width=8) (actual time=735.033..735.041 rows=11 loops=1)
  ->  Sort  (cost=217773.56..221499.13 rows=1490226 width=8) (actual time=735.031..735.033 rows=11 loops=1)
        Sort Key: (("Alias".id + 0)) DESC
        Sort Method: top-N heapsort  Memory: 25kB
        ->  Hash Semi Join  (cost=99929.33..184545.76 rows=1490226 width=8) (actual time=354.030..733.405 rows=13589 loops=1)
              Hash Cond: ("Alias".id = review.id)
              ->  Seq Scan on review "Alias"  (cost=0.00..60400.26 rows=1490226 width=4) (actual time=0.005..157.747 rows=1482065 loops=1)
              ->  Hash  (cost=81301.50..81301.50 rows=1490226 width=4) (actual time=350.842..350.842 rows=13589 loops=1)
                    Buckets: 2097152  Batches: 1  Memory Usage: 16862kB
                    ->  Hash Join  (cost=410.63..81301.50 rows=1490226 width=4) (actual time=3.363..347.392 rows=13589 loops=1)
                          Hash Cond: (review.product = category_to_product.product)
                          ->  Seq Scan on review  (cost=0.00..60400.26 rows=1490226 width=8) (actual time=0.011..144.852 rows=1482065 loops=1)
                          ->  Hash  (cost=326.86..326.86 rows=6702 width=4) (actual time=2.121..2.121 rows=100 loops=1)
                                Buckets: 8192  Batches: 1  Memory Usage: 68kB
                                ->  HashAggregate  (cost=259.84..326.86 rows=6702 width=4) (actual time=2.064..2.103 rows=100 loops=1)
                                      Group Key: category_to_product.product
                                      ->  Hash Join  (cost=12.86..243.08 rows=6702 width=4) (actual time=0.336..2.026 rows=100 loops=1)
                                            Hash Cond: (category_to_product.category = "category_product_Alias".id)
                                            ->  Seq Scan on category_to_product  (cost=0.00..194.03 rows=13403 width=8) (actual time=0.004..0.873 rows=12063 loops=1)
                                            ->  Hash  (cost=11.93..11.93 rows=74 width=4) (actual time=0.037..0.037 rows=1 loops=1)
                                                  Buckets: 1024  Batches: 1  Memory Usage: 9kB
                                                  ->  Seq Scan on category "category_product_Alias"  (cost=7.71..11.93 rows=74 width=4) (actual time=0.025..0.035 rows=1 loops=1)
                                                        Filter: ((id = 27) OR (hashed SubPlan 1))
                                                        Rows Removed by Filter: 147
                                                        SubPlan 1
                                                          ->  Nested Loop  (cost=0.00..7.71 rows=1 width=4) (actual time=0.015..0.015 rows=0 loops=1)
                                                                ->  Seq Scan on category  (cost=0.00..3.85 rows=1 width=8) (actual time=0.015..0.015 rows=0 loops=1)
                                                                      Filter: (parent = 27)
                                                                      Rows Removed by Filter: 148
                                                                ->  Seq Scan on category "category_category_product_Alias"  (cost=0.00..3.85 rows=1 width=4) (never executed)
                                                                      Filter: (id = 27)
Planning time: 0.591 ms
Execution time: 735.127 ms

更新 2 我试图简化查询:

explain analyze select
"review"."id"
from "review"
where "review"."product" in
(
select "category_to_product"."product"
from "category_to_product"
join "category"
on "category"."id" = "category_to_product"."category"
where "category"."id" = 27 or "category"."parent" = 27
)
order by "reviewty$dev"."review"."id" desc
limit 11
offset 0;

但结果变化不大

Limit  (cost=0.86..456.52 rows=11 width=4) (actual time=3354.756..3357.181 rows=11 loops=1)
  ->  Nested Loop Semi Join  (cost=0.86..1019733.07 rows=24617 width=4) (actual time=3354.754..3357.176 rows=11 loops=1)
        ->  Index Scan Backward using review_pkey on review  (cost=0.43..266561.32 rows=1490226 width=8) (actual time=0.007..391.076 rows=1054436 loops=1)
        ->  Nested Loop  (cost=0.43..0.50 rows=1 width=4) (actual time=0.002..0.002 rows=0 loops=1054436)
              ->  Index Scan using "category_to_product_B" on category_to_product  (cost=0.29..0.30 rows=1 width=8) (actual time=0.001..0.001 rows=1 loops=1054436)
                    Index Cond: (product = review.product)
              ->  Index Scan using category_pkey on category  (cost=0.14..0.17 rows=1 width=4) (actual time=0.001..0.001 rows=0 loops=1084175)
                    Index Cond: (id = category_to_product.category)
                    Filter: ((id = 27) OR (parent = 27))
                    Rows Removed by Filter: 1
Planning time: 0.434 ms
Execution time: 3357.210 ms

我现在唯一能做的就是在order by "Alias"."id" 之后附加+ 0。好难过,就像我说的,这个查询是由Prisma(prisma.io)生成的,不是我的,我想写原生sql。

更新 3 @Ancoron 是对的,set enable_nestloop = off 在运行我的查询之前会使其更快。它强制 PostgreSQL 使用hash join 而不是nested loop

Limit  (cost=10000238022.63..10000238023.45 rows=11 width=4) (actual time=629.606..629.804 rows=11 loops=1)
  ->  Merge Semi Join  (cost=10000238022.63..10000348970.97 rows=1490226 width=4) (actual time=629.605..629.797 rows=11 loops=1)
        Merge Cond: ("Alias".id = review.id)
        ->  Index Only Scan Backward using review_pkey on review "Alias"  (cost=0.43..84869.82 rows=1490226 width=4) (actual time=0.006..152.252 rows=1054436 loops=1)
              Heap Fetches: 0
        ->  Sort  (cost=10000238022.20..10000241747.77 rows=1490226 width=4) (actual time=390.996..391.000 rows=11 loops=1)
              Sort Key: review.id DESC
              Sort Method: quicksort  Memory: 1021kB
              ->  Hash Semi Join  (cost=10000000604.70..10000085221.14 rows=1490226 width=4) (actual time=4.306..388.164 rows=13589 loops=1)
                    Hash Cond: (review.product = category_to_product.product)
                    ->  Seq Scan on review  (cost=0.00..60400.26 rows=1490226 width=8) (actual time=0.004..157.976 rows=1482065 loops=1)
                    ->  Hash  (cost=10000000529.30..10000000529.30 rows=6032 width=4) (actual time=0.617..0.617 rows=100 loops=1)
                          Buckets: 8192  Batches: 1  Memory Usage: 68kB
                          ->  Merge Join  (cost=10000000008.29..10000000529.30 rows=6032 width=4) (actual time=0.555..0.603 rows=100 loops=1)
                                Merge Cond: (category_to_product.category = "category_product_Alias".id)
                                ->  Index Only Scan using "category_to_product_AB_unique" on category_to_product  (cost=0.29..419.82 rows=12063 width=8) (actual time=0.007..0.374 rows=2272 loops=1)
                                      Heap Fetches: 1123
                                ->  Index Only Scan using category_pkey on category "category_product_Alias"  (cost=10000000007.86..10000000018.82 rows=74 width=4) (actual time=0.024..0.035 rows=1 loops=1)
                                      Filter: ((id = 27) OR (hashed SubPlan 1))
                                      Rows Removed by Filter: 147
                                      Heap Fetches: 0
                                      SubPlan 1
                                        ->  Nested Loop  (cost=10000000000.00..10000000007.71 rows=1 width=4) (actual time=0.015..0.015 rows=0 loops=1)
                                              ->  Seq Scan on category  (cost=0.00..3.85 rows=1 width=8) (actual time=0.015..0.015 rows=0 loops=1)
                                                    Filter: (parent = 27)
                                                    Rows Removed by Filter: 148
                                              ->  Seq Scan on category "category_category_product_Alias"  (cost=0.00..3.85 rows=1 width=4) (never executed)
                                                    Filter: (id = 27)
Planning time: 0.594 ms
Execution time: 629.857 ms

但我问自己,为什么我必须这样做,PostgreSQL 选择了错误的计划,它使用嵌套循环而不是哈希连接,这让我的查询变慢了。它是成熟的数据库,所以当查询缓慢时我认为是我的错,我尝试创建索引,重写查询,希望 PostgreSQL 会改变它的计划,但它没有。可以接受吗?另一件事,我确信我的查询在任何情况下都会运行得更快。 这是我的 Prisma 查询:

# Write your query or mutation here
query {
  reviews (where: {
    product:{
      categories_some: {
        OR:[
          {
            id: 27
          },
          {
            parent: {
              id: 27
            }
          }
        ]
      }
    }
  }, orderBy:id_DESC, first:11, skip:0){
    id
  }
}

我没有找到其他方法来更改我的 Prisma 查询。

【问题讨论】:

  • 考虑到深层嵌套逻辑,可能是执行计划构建慢?如果是这样,那么准备好的语句将是一种改进。
  • 我认为查询可以简化为:dpaste.com/1PV1NYM如果相同,我不是100%,但我无法设置所有表格和测试数据并且您没有提供您的任何问题
  • @a_horse_with_no_name 感谢您的评论,但您的查询非常缓慢。这是它的结果:dpaste.com/3JWXQX4
  • 奇怪。这就是我测试它的方式:dpaste.com/1383N83 - 但是通过该设置,您的查询也非常快11 milliseconds2 milliseconds(我的第一个查询不正确,但不要指望这会导致差异)
  • @a_horse_with_no_name 再次运行您的查询。我的查询很慢。 dpaste.com/222FF2W

标签: sql postgresql query-performance prisma


【解决方案1】:

我的猜测是,由于表中行的敌对分布,当 PostgreSQL 尝试使用索引扫描来获取正确的顺序时,有趣的行最后出现。

尽量避免索引扫描并通过将ORDER BY 子句更改为使用显式排序

ORDER BY "Alias".id + 0 DESC

我所说的“对手分布”是什么意思?根据它的估计,PostgreSQL 认为有相当多的行满足条件,所以它认为如果它以降序处理 Alias.id 顺序的行并继续处理直到找到满足条件的 11 行,它是最便宜的。健康)状况。即使猜测是正确的,也可能是(许多)满足条件的行都具有低 Alias.id,因此它必须计算比它讨价还价的更多的行。

看到你的第二个执行计划,我怀疑至少部分问题是PostgreSQL高估了满足条件的行数:1490226而不是13589行。简化查询可能会有所帮助。

【讨论】:

  • 您有参考为什么<order-column> + 0 应该有所作为吗?
  • @Laurenz Albe 我只是更新结果,我的查询更快。您对adversary distribution of the rows 有任何参考吗?不好的是我无法更改我的查询,因为它是由 Prisma(一个 ORM 库)生成的。我必须写原生sql,我想是的。你还有其他方法吗?
  • @Ancoron 在src/backend/optimizer/path/indxpath.c 中读取match_clause_to_ordering_op
  • @Laurenz Albe 感谢您的解释。现在很清楚了。
  • 我只是在简化查询后更新结果,并没有太大变化:(
【解决方案2】:

您还可以在运行查询之前使用SET enable_nestloop = off 禁用嵌套循环连接(IDK,如果可能包含在 prisma 中)。

ORDER BY ... + 0 DESC 一样,这给了我更好的执行时间,而根本不修改查询:https://explain.depesz.com/s/Mi4W

我创建了一个完整的在线示例,其中的数据集略有减少(但仍需要一段时间才能加载)来测试不同的查询:https://dbfiddle.uk/?rdbms=postgres_10&fiddle=2c4d104804f57e1a59f7ed31bd57e2f5

如果您正在使用 prisma,那么从客户端共享您的 prisma 请求可能也是一个好主意,这会导致此 SQL 查询。也许在那方面也可以做点什么。

从查询的角度来看,使用 CTE 的优化栅栏可能会提供最好的结果:

WITH
    cte_reviews (id) AS (
        SELECT r.id
        FROM review AS r
            INNER JOIN category_to_product AS cp ON (r.product = cp.product)
        WHERE
            cp.category IN (
                SELECT 27
                UNION ALL
                SELECT id FROM category WHERE parent = 27
            )
        ORDER BY 1 ASC
    )
SELECT id
FROM cte_reviews
ORDER BY id DESC
LIMIT 11 OFFSET 0;

因此,在这里,我们强制执行前向索引扫描(仅),然后反向并限制其结果,在这种特殊情况下速度要快得多。

低至约 22 毫秒:

Planning time: 0.577 ms
Execution time: 22.021 ms

【讨论】:

  • 谢谢你,我真的很感激你所做的。您可以查看更新 3。
  • 发现了另一个更快的查询变体:dbfiddle.uk/… 但是,正如 prisma.io 声称他们正在生成最佳 SQL 一样,我很想在他们身边提交一个错误。
猜你喜欢
  • 2020-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-13
  • 1970-01-01
  • 2017-08-23
  • 1970-01-01
相关资源
最近更新 更多