将索引和 ID 主键列添加到大型 table 的最快方法是什么?

What is the fastest way to add indices and an ID primary key column to a large table?

我的 Postgres (PostgreSQL 9.6.5-1) 数据库中有大约 300 个 table。 table 很大,每个都有大约 600 万条记录。为了插入记录,我创建了不带任何索引的 tables,因为我发现不带任何索引插入要快得多。我也没有添加 ID 列(主键、自动递增、唯一)。

我现在需要为每个 table 添加索引以及一个新的 ID 列。 为此,我使用以下命令:

CREATE INDEX IF NOT EXISTS some_table_1_index ON some_table_1 (latitude, longitude, measurement_time, level, speed, altitude);
ALTER TABLE some_table_1 ADD COLUMN id SERIAL PRIMARY KEY;

我发现每个命令需要 30 到 90 秒...这意味着我需要 7 小时 30 秒才能完成所有 table 秒(假设最坏情况下每个命令需要 90 秒)。

有没有更快的方法来改变我所有的 tables?

我正在使用 Pythonpsycopg2,如果这有什么不同的话。

首先,您的命令不会创建四个索引。它创建两个索引,其中第一个是复合索引(这可能不是您想要的,因为列顺序很重要,无论规划器是否会选择使用索引)。

其次,您是否在串行执行 CREATE 命令?你能 运行 所有 300 个并行创建命令吗?

伪代码,因为我不太了解Python:

tableList = ['table1', 'table2', 'table3', ...]
createSql = 'CREATE INDEX...[0]...'
[executeInThread(table) for table in tableList]