如何减少 PostgreSQL 中长时间运行的 I/O 密集型查询的影响?
这篇文章建议我可以使用游标以限制的速率从查询中获取数据。我该怎么做?
我的目标是减少这个低优先级查询对其他高优先级查询的影响。
This post suggests I can use a cursor to fetch from a query at a throttled rate. How do I do this?
My aim is to reduce the impact of this low-priority query on other higher-priority queries.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以通过使用
DECLARE
命令声明服务器端游标来完成此操作:然后重复使用
FETCH
命令读取其结果:通过在 FETCH 命令之间休眠,您可以我们有效地限制了查询的执行速度。
完成后,您可以通过调用
COMMIT
、ROLLBACK
或CLOSE my_cursor
来删除光标。请注意,某些类型查询不能直接通过游标进行流式传输,但会在生成第一行输出之前运行完成。具有哈希聚合和大型非索引排序的查询就是一个示例。您可以降低
cursor_tuple_fraction
设置(默认 0.1)来阻止规划器选择此类计划,但这并不总是可行。You can do this by declaring server-side cursors, with the
DECLARE
command:And then read its results using the
FETCH
command repeatedly:By sleeping between the FETCH command, you're effectively limiting how fast the query can execute.
After you're done with it, you can get rid of the cursor by calling
COMMIT
,ROLLBACK
, orCLOSE my_cursor
Do note that some kinds of queries cannot be directly streamed via a cursor, but will be ran to completion before they produce the first row of output. Queries with hash aggregates and large non-indexed sorts are an example. You can lower the
cursor_tuple_fraction
setting (default 0.1) to discourage the planner to choose these sorts of plans, but it's not always possible.我知道限制光标的唯一方法是做一些工作,然后睡觉。
pg_dump 的源代码包括其“节流”算法的伪代码,但仅仅休眠固定的时间可能就足够了。
The only way I know to throttle a cursor is to do some work, then sleep.
The source code for pg_dump includes pseudo-code for its "throttle" algorithm, but just sleeping for a fixed period is probably good enough.