简体   繁体   English

使用 pg_hint_plan 时相同查询的 Postgres 查询计划更改

[英]Postgres query plan changes for identical query when using pg_hint_plan

(Postgres 11.7) (Postgres 11.7)

I'm using the Rows pg_hint_plan hint to dynamically fix a bad row-count estimate.我正在使用Rows pg_hint_plan提示来动态修复错误的行数估计。

My query accepts an array of arguments, which get unnest ed and joined onto the rest of the query as a predicate.我的查询接受一个unnest数组,这些数组被取消嵌套并连接到查询的 rest 作为谓词。 By default, the query planner always assumes this array-argument contains 100 records, whereas in reality this number could be very different.默认情况下,查询计划器总是假设这个数组参数包含 100 条记录,而实际上这个数字可能非常不同。 This bad estimate was resulting in poor query plans.这种糟糕的估计导致了糟糕的查询计划。 I set the number of rows definitively from within the calling application, by changing the hint text per query.通过更改每个查询的提示文本,我从调用应用程序中明确地设置了行数。

This approach seems to work sometimes , but I see some strange behaviour testing the query (in DBeaver).这种方法有时似乎有效,但我看到一些奇怪的行为测试查询(在 DBeaver 中)。

If I start with a brand new connection, when I explain the query (or indeed just run it), the hint seems to be ignored for the first 6 executions , but thereafter it starts getting interpreted correctly.如果我从一个全新的连接开始,当我explain查询(或者实际上只是运行它)时,前 6 次执行的提示似乎被忽略了,但此后它开始被正确解释。 This is consistently reproducible: I see the offending row count estimates change on the 7th execution on a new connection.这始终是可重现的:我看到在新连接的第 7 次执行时,有问题的行数估计值发生了变化。

More interestingly, the query also uses some ( immutable ) functions to do some lookup operations.更有趣的是,查询还使用了一些( immutable的)函数来进行一些查找操作。 If I remove these and replace them with an equivalent CTE or sub-select, this strange behaviour seems to disappear, and the hints are evaluated correctly all the time, even on a brand new connection.如果我删除这些并用等效的 CTE 或子选择替换它们,这种奇怪的行为似乎消失了,并且提示始终正确评估,即使在全新的连接上也是如此。

What could be causing it to not honour the pg_hint_plan hints until after 6 requests have been made in that session?什么可能导致它在 session 中发出 6 个请求之后才遵守pg_hint_plan提示? Why does the presence of the functions have a bearing on the hints?为什么函数的存在对提示有影响?

Since you are using JDBC, try setting the prepareThreshold connection parameter to 1, as detailed in the documentation .由于您使用的是 JDBC,请尝试将prepareThreshold连接参数设置为 1,如文档中所述

That will make the driver use a server prepared statement as soon as possible, ond it seems like this extension only works in that case.这将使驱动程序尽快使用服务器准备的语句,并且似乎此扩展仅在这种情况下有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM