返回

PG19 新特性 pg_plan_advice:查询提示的用法与风险

ClickHouse Blog AI 逐段翻译 发布 2026-11-26 04:49
直接阅读译文
DataHot 速览

PostgreSQL 19 引入两个 contrib 模块 pg_plan_advice 与 pg_stash_advice,可在会话级或按 query identifier 指定扫描方式、连接顺序、连接方法、并行度、分区连接和半连接唯一性等计划选项。其原理是告诉规划器排除未选中的选项,因此无法强制选定目标计划;也完全不校验提示优劣,陈旧或错误的提示可能显著拖慢查询。作者在 ClickHouse Managed Postgres 上演示了提示改善与恶化性能的两类场景。

为什么值得关注:对使用 PostgreSQL 做分析与报表负载的团队,这是一手实践:既说明了 PG19 计划提示的可行边界,也提示了提示漂移带来的性能风险。

译文

AI 逐段翻译

在过去的十年里,最具争议的 Postgres 功能请求之一就是查询提示。规划器在做出良好决策方面非常有效,但它并不总是如此,而查询提示被提议作为填补这一空白的方式。多年来,它们在其他数据库上一直是受欢迎的功能,有些人会说它们对于生产使用至关重要,以确保索引被有效使用并且查询被合理地规划。虽然 pg_hint_plan 已经存在了一段时间,但 Postgres 社区历史上在这个话题上存在分歧,普遍共识是规划器失败是应该修复的 bug,而不是被绕过。

Postgres 19 带来了 2 个新的 contrib 模块,它们共同提供了计划提示体验,而不影响所有查询或 SQL 语法。pg_plan_advice 在会话级别工作,允许你简单地 SET 接下来的查询将如何被规划。该技术支持相当多的功能列表,让你可以指定扫描方法、连接顺序、连接方法、并行度、分区式连接以及半连接唯一性。

随附提供的配套扩展是 pg_stash_advice。它旨在应用于查询标识符而非特定查询,因此你不使用 SET 来提供提示,而是找到一个特定的查询标识符并告诉 Postgres 始终只对该查询应用你的提示。它支持与 pg_plan_advice 相同的影响查询计划的能力,因此本文的大部分内容也适用于它。

在底层,这些扩展通过告诉规划器它不应该选择你未选择的选项来工作。这实际上不能强制 Postgres 选择你真正想要的计划,因此如果确实没有可行的方式来使用提示,建议将被部分或完全忽略。此外,没有检查建议是否良好——规划器会欣然接受会主动降低查询性能的输入。在实践中,这意味着它可以类似于你已经在使用的现有 enable_ 开关,用于强制查询使用某些计划。例如,如果你试图说服规划器使用索引,以下是你会考虑的旧方法和新方法。它们做类似的事情,但建议扩展提供了多得多的能力和粒度:

1SET enable_seqscan = off;2SELECT...;34SET pg_plan_advice.advice ='INDEX_SCAN(my_table my_table_some_idx)';5SELECT...;

场景

我整理了几个你可能想要考虑使用 pg_plan_advice 的查询示例,并做了一些测试来看看它在实践中效果如何。所有这些测试都在 ClickHouse Managed Postgres 上运行,机器为 m6gd.xlarge,具有 4 个 vCPU、16GB RAM 和 237GB 本地 NVME 驱动器。这些测试相当人工化,因为规划器非常聪明,构造可靠地给它制造麻烦的场景出奇地困难。

pg_plan_advice 作为 contrib 模块提供,因此你可能想将其添加到服务器的 shared_preload_libraries 中,或采取以下步骤之一使其在 PG19 环境中工作:

1-- session-level enablement2LOAD 'pg_plan_advice';34-- if updating PG configs is impractical, this may be a reasonable alternative.5-- keep in mind that this overwrites, so add your existing libraries too6ALTER ROLE <test_role>SET session_preload_libraries ='pg_plan_advice';

本文使用大量 SET 命令进行演示。如果你打算在生产系统中使用 pg_plan_advice,请记住这些通常应该改为在事务中使用 SET LOCAL,以防止对其他查询产生意外影响。

场景 1:ORDER BY… LIMIT

规划器通常假设表中的行分布得有些均匀。不幸的是,ISO 标准用户实际上并不存在,因此大量数据库写入集中在相关活动的突发中。这可能导致一种场景:规划器知道有百分之几的行匹配给定过滤条件,开始遍历主键列以找到它们,最终在获得足够命中之前扫描了几乎整个索引。

1CREATE TABLE events (2  id      bigint GENERATED ALWAYS ASIDENTITYPRIMARY KEY,3  status  text NOT NULL,4  payload text5);6-- let's insert generic background rows here7INSERT INTO events (status, payload)8SELECT'done', repeat('x', 100) FROM generate_series(1, 10_000_000);910-- now, let's insert the rare rows, all clustered at the end11INSERT INTO events (status, payload)12SELECT'failed', repeat('x', 100) FROM generate_series(1, 50_000);13CREATE INDEX events_status_idx ON events (status);14VACUUM ANALYZE events;

以下是我们将用于此场景的查询:

1SELECT*FROM events WHERE status ='failed'ORDERBY id LIMIT 10;

运行它确实给了我们一个糟糕的计划。

1Limit  (cost=0.43..66.77 rows=10 width=114) (actual time=1461.915..1461.919 rows=10.00 loops=1)2  Buffers: shared hit=2091443  ->  Index Scan using events_pkey on events  (cost=0.43..388915.84 rows=58625 width=114) (actual time=1461.914..1461.916 rows=10.00 loops=1)4        Filter: (status = 'failed'::text)5        Rows Removed by Filter: 100000006        Index Searches: 17        Buffers: shared hit=2091448Planning Time: 0.091 ms9Generated Plan Advice:10  INDEX_SCAN(events public.events_pkey)11  NO_GATHER(events)12Execution Time: 1461.947 ms

太好了,我们重现了失败!索引扫描看起来应该是合理的,66.77 的成本微不足道:规划器显然期望立即找到它需要的全部 10 行。不幸的是,它不得不收集并丢弃 10,000,000 行才找到一个有用的结果,这显然比预期耗时得多。

你可能也注意到了这个 explain 计划中的“Generated Plan Advice”部分。这是另一个新功能;我们在这里使用了 EXPLAIN (ANALYZE, BUFFERS, PLAN_ADVICE)。由于我们没有提供计划建议,此输出只显示它实际使用的计划。

我们当然可以通过新索引来解决这个问题,但当你在野外看到这类情况时,这并不总是一个好选择,所以让我们试试位图堆扫描。它的工作方式是首先使用位图索引扫描构建潜在行位置的位图,然后解码它以获取底层数据。它更适合批量操作,因此鉴于索引扫描被证明如此不配合,这是一个不错的选择。以下是实际使用它所需的全部操作:

1SETLOCAL pg_plan_advice.advice ='BITMAP_HEAP_SCAN(events)';

以下是新的 EXPLAIN。

1Limit  (cost=89034.29..89035.45 rows=10 width=114) (actual time=7.285..9.655 rows=10.00 loops=1)2  Buffers: shared hit=10093  ->  Gather Merge  (cost=89034.29..95705.84 rows=57283 width=114) (actual time=7.284..9.653 rows=10.00 loops=1)4        Workers Planned: 25        Workers Launched: 26        Buffers: shared hit=10097        ->  Sort  (cost=88034.26..88093.93 rows=23868 width=114) (actual time=4.096..4.098 rows=10.00 loops=3)8              Sort Key: id9              Sort Method: top-N heapsort  Memory: 27kB10              Buffers: shared hit=100911              Worker 0:  Sort Method: top-N heapsort  Memory: 27kB12              Worker 1:  Sort Method: top-N heapsort  Memory: 27kB13              ->  Parallel Bitmap Heap Scan on events  (cost=498.29..87518.48 rows=23868 width=114) (actual time=0.704..2.586 rows=16666.67 loops=3)14                    Recheck Cond: (status = 'failed'::text)15                    Heap Blocks: exact=46416                    Buffers: shared hit=99517                    Worker 0:  Heap Blocks: exact=22418                    Worker 1:  Heap Blocks: exact=22219                    ->  Bitmap Index Scan on events_status_idx  (cost=0.00..483.96 rows=57284 width=0) (actual time=1.743..1.743 rows=50000.00 loops=1)20                          Index Cond: (status = 'failed'::text)21                          Index Searches: 122                          Buffers: shared hit=4523Planning Time: 0.104 ms24Supplied Plan Advice:25  BITMAP_HEAP_SCAN(events) /* matched */26Generated Plan Advice:27  BITMAP_HEAP_SCAN(events)28  GATHER_MERGE(events)29Execution Time: 9.687 ms

并行性使其有点难以阅读,但有几点很突出。首先,我们获得了 <10ms 的执行时间,所以位图堆扫描确实有帮助。其次,我们现在可以在 EXPLAIN 输出的底部看到提供的计划建议,而匹配的反馈(没有失败标志)清楚地表明规划器实际使用了我们的建议。请注意,这并不一定意味着规划器从建议中获益。

场景 2:JOIN 相关性

JOIN 可能是规划器复杂性的来源,因为统计信息坚决是单表的。规划器预测 JOIN 表上的过滤条件将修剪多少行的能力有限,因此它可能严重偏离选择性。一般来说,它假设不同表上的过滤条件彼此独立,而使用以下设置很容易违反这一假设:

1CREATE TABLE accounts (id intPRIMARY KEY, plan text NOT NULL);2INSERT INTO accounts3SELECT g, CASEWHEN g %100=0THEN'enterprise'ELSE'standard'END4FROM generate_series(1, 1_000_000) g;5CREATE INDEX ON accounts (plan);67CREATE TABLE actions (id bigintPRIMARY KEY, account_id intNOT NULL, kind text NOT NULL, created_at timestamptz NOT NULL);8-- baseline rows9INSERT INTO actions10SELECT g, 1+ (random() *999999)::int,11       (ARRAY['login','view','edit','sync'])[1+ (g %4)],12       now() - random() *interval'90 days'13FROM generate_series(1, 10_000_000) g;14-- trial_start rows, randomly spread across non-enterprise accounts15INSERT INTO actions16SELECT10_000_000 + g,17       (1+ (random() *999998)::int) /100*100+1+ (random() *98)::int,  -- never a multiple of 10018'trial_start',19       now() - random() *interval'90 days'20FROM generate_series(1, 500_000) g;21-- a handful of trial_start rows for enterprise accounts, also scattered randomly22INSERT INTO actions23SELECT20_000_000 + g, 100* (1+ (random() *9999)::int), 'trial_start',24       now() - random() *interval'90 days'25FROM generate_series(1, 20) g;2627CREATE INDEX actions_created_at_idx   ON actions (created_at);28CREATE INDEX actions_account_kind_idx ON actions (account_id, kind);29CREATE INDEX actions_kind_idx         ON actions (kind);30VACUUM ANALYZE accounts, actions;

以下是我们的基线查询。它只是一个简单的连接、过滤和限制:

1SELECT act.*2FROM actions act JOIN accounts a ON a.id = act.account_id3WHERE a.plan ='enterprise'AND act.kind ='trial_start'4ORDERBY act.created_at DESC5LIMIT 10;

以下是我们的第一个计划,规划器为我们承担了繁重的工作:

1Limit  (cost=0.86..1017.87 rows=10 width=25) (actual time=742.602..3836.972 rows=10.00 loops=1)2    Buffers: shared hit=47651763    ->  Nested Loop  (cost=0.86..537793.14 rows=5288 width=25) (actual time=742.602..3836.963 rows=10.00 loops=1)4          Buffers: shared hit=47651765          ->  Index Scan Backward using actions_created_at_idx on actions act  (cost=0.43..300345.83 rows=513441 width=25) (actual time=0.012..3153.670 rows=190851.00 loops=1)6                Filter: (kind = 'trial_start'::text)7                Rows Removed by Filter: 38001048                Index Searches: 19                Buffers: shared hit=400181210          ->  Index Scan using accounts_pkey on accounts a  (cost=0.42..0.46 rows=1 width=4) (actual time=0.003..0.003 rows=0.00 loops=190851)11                Index Cond: (id = act.account_id)12                Filter: (plan = 'enterprise'::text)13                Rows Removed by Filter: 114                Index Searches: 19085115                Buffers: shared hit=76336416  Planning:17    Buffers: shared hit=1618  Planning Time: 0.262 ms19  Generated Plan Advice:20    JOIN_ORDER(act a)21    NESTED_LOOP_PLAIN(a)22    INDEX_SCAN(act public.actions_created_at_idx a public.accounts_pkey)23    NO_GATHER(act a)24  Execution Time: 3837.021 ms

说实话,这个计划相当糟糕。规划器正确地理解大约有 500K 行 trial_start 行,以及 1% 的客户是 enterprise客户。然后它将这些数字相互相乘,从而预测会有 5000 行匹配,而它只需要 10 行。不幸的是,这些过滤条件并不像它估计的那样相互独立,因此在 50 万行中实际上只有 20 行具有它正在寻找的值。因此,为了得到这个结果,它最终扫描的行数远远超过它原本的预期。从上面的行估计中可以看出这一点:规划器预测有 5288 行,而我们知道只有 20 行,这与计算结果完全吻合。

为了解决这个问题,让我们尝试给出计划建议。我们希望连接顺序优先考虑 accounts,因为这将为我们提供一个选择性高得多的过滤器,从而减少行数。

1SETLOCAL pg_plan_advice.advice ='JOIN_ORDER(a act)';

以下是它给出的结果:

1Limit  (cost=16804.99..16806.16 rows=10 width=25) (actual time=17.673..20.267 rows=10.00 loops=1)2    Buffers: shared hit=354863    ->  Gather Merge  (cost=16804.99..17420.75 rows=5287 width=25) (actual time=17.672..20.264 rows=10.00 loops=1)4          Workers Planned: 25          Workers Launched: 26          Buffers: shared hit=354867          ->  Sort  (cost=15804.97..15810.48 rows=2203 width=25) (actual time=14.854..14.856 rows=5.00 loops=3)8                Sort Key: act.created_at DESC9                Sort Method: quicksort  Memory: 25kB10                Buffers: shared hit=3548611                Worker 0:  Sort Method: quicksort  Memory: 25kB12                Worker 1:  Sort Method: quicksort  Memory: 25kB13                ->  Nested Loop  (cost=90.58..15757.36 rows=2203 width=25) (actual time=2.455..14.835 rows=6.67 loops=3)14                      Buffers: shared hit=3547015                      ->  Parallel Bitmap Heap Scan on accounts a  (cost=90.15..5425.23 rows=4292 width=4) (actual time=0.724..3.204 rows=3333.33 loops=3)16                            Recheck Cond: (plan = 'enterprise'::text)17                            Heap Blocks: exact=198618                            Buffers: shared hit=545719                            Worker 0:  Heap Blocks: exact=171320                            Worker 1:  Heap Blocks: exact=170721                            ->  Bitmap Index Scan on accounts_plan_idx  (cost=0.00..87.57 rows=10300 width=0) (actual time=1.202..1.202 rows=10000.00 loops=1)22                                  Index Cond: (plan = 'enterprise'::text)23                                  Index Searches: 124                                  Buffers: shared hit=1125                      ->  Index Scan using actions_account_kind_idx on actions act  (cost=0.43..2.40 rows=1 width=25) (actual time=0.003..0.003 rows=0.00 loops=10000)26                            Index Cond: ((account_id = a.id) AND (kind = 'trial_start'::text))27                            Index Searches: 1000028                            Buffers: shared hit=3001329  Planning:30    Buffers: shared hit=1631  Planning Time: 0.269 ms32  Supplied Plan Advice:33    JOIN_ORDER(a act) /* matched */34  Generated Plan Advice:35    JOIN_ORDER(a act)36    NESTED_LOOP_PLAIN(act)37    BITMAP_HEAP_SCAN(a)38    INDEX_SCAN(act public.actions_account_kind_idx)39    GATHER_MERGE((act a))40  Execution Time: 20.309 ms

接近 200 倍的提升简直好得离谱。通过调整连接顺序,我们能够充分利用 accounts 表中匹配 enterprise 过滤条件的行数少得多的优势,这让我们能够大幅减少需要扫描的行数。在生产环境的大多数情况下,你很可能不会获得这么大的加速,但这种模式时不时就会出现,而拥有一个能应对它的工具是无价的。

这可能是最适合计划建议功能的用例。它很罕见,但没有多少好的替代方案可以应对它。我大概遇到过五六次类似的挑战,虽然我能够找到变通方法,但它们变得相当取巧且难以推理。

场景 3:处理过时的提示

我们在场景 1 中取得了一些有希望的结果,但如果数据发生变化、变得不那么成块,而我们的提示仍然存在,会发生什么?为了测试这一点,让我们把每第三行设为 failed 状态:

1UPDATE events SET status ='failed'WHERE id %3=0;2VACUUM ANALYZE events;

这意味着我们只需要遍历几行就能找到我们要找的内容,因此规划器的估计应该能给我们带来好的结果。果然,如果我们在没有任何提示的情况下运行,我们会得到:

1Limit  (cost=0.43..1.86 rows=10 width=114) (actual time=0.021..0.031 rows=10.00 loops=1)2  Buffers: shared hit=233  ->  Index Scan using events_pkey on events  (cost=0.43..497822.11 rows=3496879 width=114) (actual time=0.020..0.029 rows=10.00 loops=1)4        Filter: (status = 'failed'::text)5        Rows Removed by Filter: 206        Index Searches: 17        Buffers: shared hit=238Planning Time: 0.091 ms9Generated Plan Advice:10  INDEX_SCAN(events public.events_pkey)11  NO_GATHER(events)12Execution Time: 0.052 ms

这正是我们一开始想要看到的那种结果!让我们看看使用先前那个改用位图堆扫描的提示会怎样:

1Limit  (cost=357696.74..357697.90 rows=10 width=114) (actual time=365.137..368.829 rows=10.00 loops=1)2  Buffers: shared hit=645403  ->  Gather Merge  (cost=357696.74..764965.92 rows=3496879 width=114) (actual time=365.136..368.826 rows=10.00 loops=1)4        Workers Planned: 25        Workers Launched: 26        Buffers: shared hit=645407        ->  Sort  (cost=356696.71..360339.30 rows=1457033 width=114) (actual time=361.889..361.890 rows=7.00 loops=3)8              Sort Key: id9              Sort Method: top-N heapsort  Memory: 27kB10              Buffers: shared hit=6454011              Worker 0:  Sort Method: top-N heapsort  Memory: 27kB12              Worker 1:  Sort Method: top-N heapsort  Memory: 27kB13              ->  Parallel Bitmap Heap Scan on events  (cost=31349.45..325210.75 rows=1457033 width=114) (actual time=102.727..260.178 rows=1127777.67 loops=3)14                    Recheck Cond: (status = 'failed'::text)15                    Rows Removed by Index Recheck: 216                    Heap Blocks: exact=9604 lossy=1095717                    Buffers: shared hit=6452618                    Worker 0:  Heap Blocks: exact=9577 lossy=1103419                    Worker 1:  Heap Blocks: exact=9675 lossy=1097220                    ->  Bitmap Index Scan on events_status_idx  (cost=0.00..30475.23 rows=3496879 width=0) (actual time=100.233..100.234 rows=3383333.00 loops=1)21                          Index Cond: (status = 'failed'::text)22                          Index Searches: 123                          Buffers: shared hit=266724Planning Time: 0.127 ms25Supplied Plan Advice:26  BITMAP_HEAP_SCAN(events) /* matched */27Generated Plan Advice:28  BITMAP_HEAP_SCAN(events)29  GATHER_MERGE(events)30Execution Time: 368.866 ms

这差了 7000 倍,而反馈没有显示问题,因为它仍然 匹配。既然干扰规划器的人工数据条件已经消失,规划器完全可以比我们提示的替代方案做得更好。这是一个很好的提醒:所有提示都应定期检查是否仍有必要——否则,你的性能修复可能会导致性能问题。

结论

我们已经看过几个场景,很明显 pg_plan_advice 是一个强大但视情况而定的工具。要构造出能可靠地迷惑规划器的场景并不容易,但它们在 production 中出现的频率足够高,因此值得拥有一个工具来应对它们。pg_plan_advice 还足够新,很难确定地说,但根据我在这里展示的内容,我敢打赌以下工作流程会对你很有帮助:

  1. 如果你遇到一个莫名其妙变慢的查询,而且调优没有达到你想要的结果,那么计划建议是一个值得尝试的好办法。
  2. 你还可以用 pg_stash_advice 将其与查询 ID 关联起来。如果你这样做,请注意这需要针对 HA 故障转移进行特殊处理,因为它不会写入 WAL 日志,而且尚未得到充分探索。

如果你确实设置了建议,请在几个月后检查它,因为数据的变化和查询模式的变化可能会使它适得其反。

阅读记录仅保存在当前浏览器,用于「为你」推荐。管理阅读记录

这篇内容对你有用吗?

反馈只用于改善内容筛选,不等同于收藏

分享这条资讯
分享海报
保存图片
iOS 也可以长按图片保存