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

use*_*284 0 postgresql postgresql-9.3

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

我可以

select relname from pg_class where relkind='i'; and drop index
Run Code Online (Sandbox Code Playgroud)

但我认为这个查询也会删除一些系统表。我如何做到这一点而不影响数据库的功能?

小智 5

如果您要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');
Run Code Online (Sandbox Code Playgroud)

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

如果你想排除主键索引,你可以使用这样的东西:

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;
Run Code Online (Sandbox Code Playgroud)

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