向现有 postgres 索引添加唯一约束的性能影响

Sel*_*osi 5 postgresql indexing database-migration unique-constraint

我们在 postgres 中有一个相当大的表,在一些重构过程中,我们意识到现有 UUID 列上有一个索引,但它缺乏唯一约束。

有没有人有任何应用ALTER TABLE ... ADD CONSTRAINTala https://www.postgresql.org/docs/9.4/indexes-unique.html 的经验以及运行时影响是什么?

尝试评估实时执行此操作与停机对运行时的影响。我们已经在 db 副本上对其进行了测试,但是很难模拟生产流量负载,只是寻找一些东西来检查是否有人有经验。

Jer*_*emy 9

要在不停机的情况下完成此操作,您应该分两步完成:

  1.  CREATE UNIQUE INDEX CONCURRENTLY idx_name ON table_name (id);
    
    Run Code Online (Sandbox Code Playgroud)
  2.  ALTER TABLE table_name ADD CONSTRAINT constraint_name UNIQUE(id) 
     USING INDEX idx_name;
    
    Run Code Online (Sandbox Code Playgroud)