如何删除 postgres 中的所有无效索引?

How do I drop all invalid indexes in postgres?

使用这个查询:

我有数百个无效索引:

SELECT * FROM pg_class, pg_index WHERE pg_index.indisvalid = false AND pg_index.indexrelid = pg_class.oid;

 public  | post_aggregates_pkey_ccnew_ccnew_ccnew1
 public  | post_aggregates_post_id_key_ccnew_ccnew_ccnew1
 public  | idx_post_aggregates_stickied_hot_ccnew_ccnew_ccnew1
 public  | idx_post_aggregates_hot_ccnew_ccnew_ccnew1
...

它们似乎没有被使用,我不知道为什么要创建它们(在我看来它们不应该保留),因为原始索引仍然存在。

你需要dynamic commands inside a function or anonymous code block.

do $$
declare
    rec record;
begin
    for rec in
        select relnamespace::regnamespace as namespace, relname
        from pg_index i
        join pg_class c on c.oid = i.indexrelid
        where not indisvalid
    loop
        execute format('drop index %s.%s', rec.namespace, rec.relname);
        -- optionally:
        -- raise notice '%', format('drop index %s.%s', rec.namespace, rec.relname);
    end loop;
end $$;

Postgres 在 CREATE TABLEALTER TABLE 中创建或更改 table 约束时自动创建索引。除此之外,它从不自己创建索引。

无效索引的最可能原因是不小心使用了 CREATE [UNIQUE] INDEX CONCURRENTLY 命令。当命令在并行事务中执行时,极有可能发生死锁,导致命令失败并留下无效索引。并发创建唯一性索引时,违反唯一性也可能导致失败。

并发索引应该在了解这些问题的管理员的严格控制下,尤其是当它定期自动执行时。

the documentation.

中阅读更多内容