使用 psycopg2 删除索引在提交之前或之后生效?

To drop an index with psycopg2 takes effect before or after commit?

我正在执行 python 脚本以将多个数据插入 postgresql 数据库。

遵循 postgresql documentation 为了加快加载过程我的脚本有这种结构

所以我的问题是:在提交之前删除索引是否对加速加载有任何影响?

commit 只是将任何正在进行的事务提交到您的数据库。

您实际上是在问,是否删除索引然后在同一事务中进行复制是否会提供与首先在一个事务中删除索引然后在新事务中复制数据相同的加速。

docs 的直接引用是这样说的:

If you are adding large amounts of data to an existing table, it might be a win to drop the indexes, load the table, and then recreate the indexes. Of course, the database performance for other users might suffer during the time the indexes are missing. One should also think twice before dropping a unique index, since the error checking afforded by the unique constraint will be lost while the index is missing.

粗体部分间接告诉你应该在删除索引后提交,因为删除索引而不提交(完成事务)不应该对数据库的其他用户产生任何影响。

所以解决方案应该是这样的:

删除索引,提交,复制数据,创建新索引并再次提交。

请注意,当您将事务拆分为两个事务时,您就失去了原子性。 IE。有可能您的索引已删除,但没有复制任何数据(例如,如果在复制事务期间电源或网络丢失)并且永远不会重新创建索引。