如何在 PostgreSQL 中进行大型非阻塞更新?
我想对 PostgreSQL 中的表进行大型更新,但我不需要在整个操作中维护事务完整性,因为我知道我要更改的列不会在更新期间被写入或读取更新。 我想知道 psql 控制台中是否有一种简单的方法可以使这些类型的操作更快。
例如,假设我有一个名为“orders”的表,包含 3500 万行,我想这样做:
UPDATE orders SET status = null;
为了避免被转移到离题讨论,让我们假设当前设置了 3500 万列的所有状态值到相同的(非空)值,从而使索引变得无用。
该语句的问题在于需要很长时间才能生效(完全是因为锁定),并且所有更改的行都被锁定,直到整个更新完成。 此更新可能需要 5 小时,而类似的更新
UPDATE orders SET status = null WHERE (order_id > 0 and order_id < 1000000);
可能需要 1 分钟。 超过 3500 万行,执行上述操作并将其分成 35 个块只需要 35 分钟,为我节省了 4 小时 25 分钟。
我可以使用脚本进一步分解它(此处使用伪代码):
for (i = 0 to 3500) {
db_operation ("UPDATE orders SET status = null
WHERE (order_id >" + (i*1000)"
+ " AND order_id <" + ((i+1)*1000) " + ")");
}
此操作可能只需几分钟即可完成,而不是 35 分钟。
所以这就是我真正要问的。 我不想每次想做这样的大型一次性更新时都编写一个奇怪的脚本来破坏操作。 有没有办法完全在 SQL 中完成我想要的事情?
I want to do a large update on a table in PostgreSQL, but I don't need the transactional integrity to be maintained across the entire operation, because I know that the column I'm changing is not going to be written to or read during the update. I want to know if there is an easy way in the psql console to make these types of operations faster.
For example, let's say I have a table called "orders" with 35 million rows, and I want to do this:
UPDATE orders SET status = null;
To avoid being diverted to an offtopic discussion, let's assume that all the values of status for the 35 million columns are currently set to the same (non-null) value, thus rendering an index useless.
The problem with this statement is that it takes a very long time to go into effect (solely because of the locking), and all changed rows are locked until the entire update is complete. This update might take 5 hours, whereas something like
UPDATE orders SET status = null WHERE (order_id > 0 and order_id < 1000000);
might take 1 minute. Over 35 million rows, doing the above and breaking it into chunks of 35 would only take 35 minutes and save me 4 hours and 25 minutes.
I could break it down even further with a script (using pseudocode here):
for (i = 0 to 3500) {
db_operation ("UPDATE orders SET status = null
WHERE (order_id >" + (i*1000)"
+ " AND order_id <" + ((i+1)*1000) " + ")");
}
This operation might complete in only a few minutes, rather than 35.
So that comes down to what I'm really asking. I don't want to write a freaking script to break down operations every single time I want to do a big one-time update like this. Is there a way to accomplish what I want entirely within SQL?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
列/行
PostgreSQL 的 MVCC 模型 中的任何
UPDATE
都会写入一个整行的新版本。 如果并发事务更改同一行的任何列,则会出现耗时的并发问题。 手册中的详细信息。了解相同的< em>列不会被并发事务触及,可以避免一些可能出现的复杂情况,但不能避免其他情况。指数
更新整个表(或其主要部分)时,Postgres从不使用索引。 当必须读取所有或大多数行时,顺序扫描速度更快。 相反:索引维护意味着
UPDATE
的额外成本。表现
我知道您的目标是寻求更通用的解决方案(见下文)。 但要解决实际问题:无论表大小如何,都可以在几毫秒内处理:
手册(最多 Postgres 10):
手册(自 Postgres 11 起):
和:
确保您没有依赖于列的对象(外键约束、索引、视图...)。 您需要删除/重新创建它们。 除此之外,系统目录表 pg_attribute 上的微小操作即可完成这项工作。 需要表上的独占锁,这对于高并发负载可能会出现问题。 (就像布尔曼在他的
如果您想要保留列默认值,请在单独的命令中将其添加回来。。 在同一命令中执行此操作会立即将其应用于所有行。 请参阅:
实际应用默认情况下,考虑批量执行:
一般解决方案
更新:从 Postgres 11 开始,您可以使用
PROCEDURE
为此,您可以在其中包含事务控制语句,例如COMMIT
。 请参阅:dblink
已在另一个答案中提到。 它允许通过隐式单独连接访问“远程”Postgres 数据库。 “远程”数据库可以是当前数据库,从而实现“自主事务”:函数在“远程”数据库中写入的内容已提交且无法回滚。这允许运行单个函数,以较小的部分更新大表,并且每个部分单独提交。 避免为大量行增加事务开销,更重要的是,在每个部分之后释放锁。 这使得并发操作能够在没有太多延迟的情况下继续进行,并减少死锁的可能性。
如果您没有并发访问,这几乎没有用 - 除非在异常后避免
ROLLBACK
。 对于这种情况,还要考虑SAVEPOINT
。免责声明
首先,大量小额交易实际上更昂贵。 这仅对大表有意义。 最佳位置取决于许多因素。
如果您不确定自己在做什么:单笔交易是安全的方法。 为了使其正常工作,表上的并发操作必须配合。 例如:并发写入可以将行移动到假定已经处理的分区。 或者并发读取可能会看到不一致的中间状态。 您已收到警告。
分步说明
需要首先安装附加模块 dblink:
设置与 dblink 的连接很大程度上取决于数据库集群的设置和适当的安全策略。 这可能很棘手。 相关的后续答案更多如何与 dblink 连接:
按照指示创建一个
FOREIGN SERVER
和USER MAPPING
以简化连接(除非你已经有一个)。假设
串行主键
有或没有一些间隙。调用:
您可以根据需要对任何部分进行参数化:表名、列名、值……只需确保清理标识符以避免 SQL 注入:
避免空更新:
Column / Row
Any
UPDATE
in PostgreSQL's MVCC model writes a new version of the whole row. If concurrent transactions change any column of the same row, time-consuming concurrency issues arise. Details in the manual. Knowing the same column won't be touched by concurrent transactions avoids some possible complications, but not others.Index
When updating the whole table (or major parts of it) Postgres never uses an index. A sequential scan is faster when all or most rows have to be read. On the contrary: Index maintenance means additional cost for the
UPDATE
.Performance
I understand you are aiming for a more general solution (see below). But to address the actual question asked: This can be dealt with in a matter milliseconds, regardless of table size:
The manual (up to Postgres 10):
The manual (since Postgres 11):
And:
Make sure you don't have objects depending on the column (foreign key constraints, indices, views, ...). You would need to drop / recreate those. Barring that, tiny operations on the system catalog table
pg_attribute
do the job. Requires an exclusive lock on the table which may be a problem for heavy concurrent load. (Like Buurman emphasizes in his comment.) Baring that, the operation is a matter of milliseconds.If you have a column default you want to keep, add it back in a separate command. Doing it in the same command applies it to all rows immediately. See:
To actually apply the default, consider doing it in batches:
General solution
Update: Since Postgres 11 you can use a
PROCEDURE
for the purpose, where you can include transaction control statements likeCOMMIT
. See:dblink
has been mentioned in another answer. It allows access to "remote" Postgres databases in implicit separate connections. The "remote" database can be the current one, thereby achieving "autonomous transactions": what the function writes in the "remote" db is committed and can't be rolled back.This allows to run a single function that updates a big table in smaller parts and each part is committed separately. Avoids building up transaction overhead for very big numbers of rows and, more importantly, releases locks after each part. This allows concurrent operations to proceed without much delay and makes deadlocks less likely.
If you don't have concurrent access, this is hardly useful - except to avoid
ROLLBACK
after an exception. Also considerSAVEPOINT
for that case.Disclaimer
First of all, lots of small transactions are actually more expensive. This only makes sense for big tables. The sweet spot depends on many factors.
If you are not sure what you are doing: a single transaction is the safe method. For this to work properly, concurrent operations on the table have to play along. For instance: concurrent writes can move a row to a partition that's supposedly already processed. Or concurrent reads can see inconsistent intermediary states. You have been warned.
Step-by-step instructions
The additional module dblink needs to be installed first:
Setting up the connection with dblink very much depends on the setup of your DB cluster and security policies in place. It can be tricky. Related later answer with more how to connect with dblink:
Create a
FOREIGN SERVER
and aUSER MAPPING
as instructed there to simplify and streamline the connection (unless you have one already).Assuming a
serial PRIMARY KEY
with or without some gaps.Call:
You can parameterize any part according to your needs: the table name, column name, value, ... just be sure to sanitize identifiers to avoid SQL injection:
Avoid empty UPDATEs:
您应该将此列委托给另一个表,如下所示:
然后您设置 status=NULL 的操作将是即时的:
You should delegate this column to another table like this:
Then your operation of setting status=NULL will be instant:
Postgres 使用 MVCC(多版本并发控制),因此如果您是唯一的写入者,则可以避免任何锁定; 任意数量的并发读取器都可以在该表上工作,并且不会有任何锁定。
因此,如果确实需要 5 小时,则一定是出于不同的原因(例如,您确实有并发写入,与您声称没有的相反)。
Postgres uses MVCC (multi-version concurrency control), thus avoiding any locking if you are the only writer; any number of concurrent readers can work on the table, and there won't be any locking.
So if it really takes 5h, it must be for a different reason (e.g. that you do have concurrent writes, contrary to your claim that you don't).
首先 - 您确定需要更新所有行吗?
也许某些行的
status
已经为 NULL?如果是这样,那么:
至于对更改进行分区 - 这在纯 sql 中是不可能的。 所有更新都在单个事务中。
在“纯 sql”中执行此操作的一种可能方法是安装 dblink,使用 dblink 连接到同一数据库,然后通过 dblink 发出大量更新,但对于这样一个简单的任务来说,这似乎有点矫枉过正。
通常只需添加适当的
where
即可解决问题。 如果没有 - 只需手动分区即可。 编写脚本太多了 - 您通常可以用简单的一行代码来编写它:为了可读性,我在此处换行,通常是一行。 上述命令的输出可以直接输入到 psql:
或者先输入到文件,然后输入到 psql(以防您稍后需要该文件):
First of all - are you sure that you need to update all rows?
Perhaps some of the rows already have
status
NULL?If so, then:
As for partitioning the change - that's not possible in pure sql. All updates are in single transaction.
One possible way to do it in "pure sql" would be to install dblink, connect to the same database using dblink, and then issue a lot of updates over dblink, but it seems like overkill for such a simple task.
Usually just adding proper
where
solves the problem. If it doesn't - just partition it manually. Writing a script is too much - you can usually make it in a simple one-liner:I wrapped lines here for readability, generally it's a single line. Output of above command can be fed to psql directly:
Or first to file and then to psql (in case you'd need the file later on):
我绝不是 DBA,但是经常需要更新 3500 万行的数据库设计可能会存在……问题。
一个简单的
WHERE status IS NOT NULL
可能会大大加快速度(假设您有状态索引) - 不知道实际用例,我假设如果经常运行,这是一个很好的选择3500 万行中的一部分可能已经处于空状态。但是,您可以通过 循环语句。 我将编写一个小示例:
然后可以通过执行类似以下操作来运行它:
您可能想要选择行计数,但请注意确切的行计数可能需要很长时间。 PostgreSQL wiki 有一篇关于缓慢计数以及如何避免它的文章。
此外,“RAISE NOTICE”部分只是用来跟踪脚本的进展情况。 如果您不关注通知,或者不关心,最好将其忽略。
I am by no means a DBA, but a database design where you'd frequently have to update 35 million rows might have… issues.
A simple
WHERE status IS NOT NULL
might speed up things quite a bit (provided you have an index on status) – not knowing the actual use case, I'm assuming if this is run frequently, a great part of the 35 million rows might already have a null status.However, you can make loops within the query via the LOOP statement. I'll just cook up a small example:
It can then be run by doing something akin to:
You might want to select the row count, but beware that the exact row count can take a lot of time. The PostgreSQL wiki has an article about slow counting and how to avoid it.
Also, the RAISE NOTICE part is just there to keep track on how far along the script is. If you're not monitoring the notices, or do not care, it would be better to leave it out.
您确定这是因为锁定吗? 我不这么认为,还有很多其他可能的原因。 要找出答案,您始终可以尝试仅进行锁定。 尝试这个:
开始;
现在选择();
从订单中选择*进行更新;
现在选择();
回滚;
要了解真正发生的情况,您应该首先运行 EXPLAIN(EXPLAIN UPDATE order SET status...)和/或 EXPLAIN ANALYZE。 也许您会发现您没有足够的内存来有效地执行更新。 如果是,则将 work_mem 设置为 'xxxMB'; 可能是一个简单的解决方案。
另外,跟踪 PostgreSQL 日志以查看是否出现一些与性能相关的问题。
Are you sure this is because of locking? I don't think so and there's many other possible reasons. To find out you can always try to do just the locking. Try this:
BEGIN;
SELECT NOW();
SELECT * FROM order FOR UPDATE;
SELECT NOW();
ROLLBACK;
To understand what's really happening you should run an EXPLAIN first (EXPLAIN UPDATE orders SET status...) and/or EXPLAIN ANALYZE. Maybe you'll find out that you don't have enough memory to do the UPDATE efficiently. If so, SET work_mem TO 'xxxMB'; might be a simple solution.
Also, tail the PostgreSQL log to see if some performance related problems occurs.
我会使用 CTAS:
I would use CTAS:
一些尚未提及的选项:
使用新表技巧。 在您的情况下,您可能需要做的是编写一些触发器来处理它,以便对原始表的更改也会传播到您的表副本,类似这样......(percona 是一个以触发方式执行此操作的示例)。 另一种选择可能是“创建一个新列,然后用它替换旧列”技巧,以避免锁定(不清楚是否有助于提高速度)。
可能计算最大 ID,然后生成“您需要的所有查询”并将它们作为单个查询传递,例如 update X set Y = NULL where ID
10000 且 ID >= 0; 更新 X 设置 Y = NULL,其中 ID < 20000和ID> 10000; ...
那么它可能不会做那么多的锁定,并且仍然是所有 SQL,尽管你确实有额外的逻辑来做到这一点:(Some options that haven't been mentioned:
Use the new table trick. Probably what you'd have to do in your case is write some triggers to handle it so that changes to the original table also go propagated to your table copy, something like that... (percona is an example of something that does it the trigger way). Another option might be the "create a new column then replace the old one with it" trick, to avoid locks (unclear if helps with speed).
Possibly calculate the max ID, then generate "all the queries you need" and pass them in as a single query like
update X set Y = NULL where ID < 10000 and ID >= 0; update X set Y = NULL where ID < 20000 and ID > 10000; ...
then it might not do as much locking, and still be all SQL, though you do have extra logic up front to do it :(PostgreSQL 版本 11 使用 具有非 NULL 默认值的快速 ALTER TABLE ADD COLUMN< /a> 功能。 如果可能,请升级到版本 11。
这篇博文中提供了解释。
PostgreSQL version 11 handles this for you automatically with the Fast ALTER TABLE ADD COLUMN with a non-NULL default feature. Please do upgrade to version 11 if possible.
An explanation is provided in this blog post.