如何从 postgres 数据库中删除所有索引表?

How to delete all index tables from postgres database?

我的数据库中有很多索引表。我想删除它们并只索引那些非常大的表。我怎样才能删除它们?

我可以

select relname from pg_class where relkind='i'; and drop index

但我认为这个查询也会删除一些系统表。我如何在不影响数据库功能的情况下执行此操作?

如果您使用 pg_class 查找所有索引,则需要将其连接到 pg_namespace 并过滤存储表(和索引)的架构。

不过 pg_indexes 更容易:

select schemaname, 
       indexname, 
       tablename, 
       format('drop index %I.%I;', schemaname, indexname) as drop_statement
from pg_indexes
where schemaname not in ('pg_catalog', 'pg_toast');

然而,这也会向您显示用于主键的索引。

如果要排除主键索引,可以这样使用:

select s.nspname as schemaname,
       i.relname as indexname,
       t.relname as tablename,
       format('drop index %I.%I;', s.nspname, i.relname) as drop_statement
from pg_index idx
  join pg_class i on i.oid = idx.indexrelid
  join pg_class t on t.oid = idx.indrelid
  join pg_namespace s on i.relnamespace = s.oid
where s.nspname  not in ('pg_catalog', 'pg_toast')
  and not idx.indisprimary;

如果您还想排除唯一索引,只需将 and not idx.indisunique 添加到 where 条件即可。