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

我正在做一个
python脚本,将几个数据插入postgresql数据库.

在postgresql documentation之后,为了加快加载过程,我的脚本具有这种结构

>连接到数据库并创建游标
>删除所有索引
>使用’copy’命令加载所有数据
>重新创建所有索引
>提交并关闭游标和连接(仅在整个脚本中提交)

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

最佳答案 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.

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

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

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

请注意,当您将事务拆分为两个事务时,会失去原子性.即您的索引可能会被删除,但不会复制数据(例如,如果在复制事务期间电源或网络丢失),则永远不会重新创建索引.

点赞