PG建立or修改索引

pgsql中的索引不能重名,重名的建立失败。sql

 

建立二级索引的命令:create index CONCURRENTLY idx_abc on tb1(a,b);数据库

 

注意:reindex 重建索引的过程是阻塞的,通常大表不建议使用这个命令,能够重建一个索引,而后删除老的索引。ide

 

下面看一个《PostgreSQL实战》书上page202的例子:工具

因为PGMVCC机制,当运行大量的更新操做后,会有索引膨胀的现象。这时候 能够经过 create index concurrently 不阻塞查询和更新的状况下,在线从新重建索引,建立好索引以后,再删除原先的索引,减小索引的尺寸,提升查询速度。对于主键也能够使用这种方式进行,例如:fetch

db1=# \d testdataspa

                 Table "public.testdata"索引

  Column  |     Type     | Collation | Nullable | Default it

----------+--------------+-----------+----------+---------io

 id       | integer      |           | not null | table

 course   | integer      |           |          |

 grade    | numeric(4,2) |           |          |

 testtime | date         |           |          |

Indexes:

    "testdata_pkey" PRIMARY KEY, btree (id)

 

db1=# create unique index concurrently on testdata using btree(id);

 

db1=# select

schemaname,

relname,

indexrelname,

pg_relation_size (indexrelid) as index_size,

idx_scan,

idx_tup_read,

idx_tup_fetch

from pg_stat_user_indexes where

indexrelname in (select indexname from pg_indexes where schemaname ='public' and tablename='testdata');

 schemaname | relname  |  indexrelname   | index_size | idx_scan | idx_tup_read | idx_tup_fetch

------------+----------+-----------------+------------+----------+--------------+---------------

 public     | testdata | testdata_pkey   |      16384 |        2 |      5999998 |       5999998

 public     | testdata | testdata_id_idx |      16384 |        0 |            0 |             0

(2 rows)

 

db1=# begin;

BEGIN

 

db1=# alter table testdata drop constraint testdata_pkey;

ALTER TABLE

 

db1=# alter table testdata add constraint testdata_id_idx primary key using index testdata_id_idx ;

ALTER TABLE

 

db1=# end;

COMMIT

 

db1=# \d testdata

                 Table "public.testdata"

  Column  |     Type     | Collation | Nullable | Default

----------+--------------+-----------+----------+---------

 id       | integer      |           | not null |

 course   | integer      |           |          |

 grade    | numeric(4,2) |           |          |

 testtime | date         |           |          |

Indexes:

    "testdata_id_idx" PRIMARY KEY, btree (id)

 

db1=# select

schemaname,

relname,

indexrelname,

pg_relation_size (indexrelid) as index_size,

idx_scan,

idx_tup_read,

idx_tup_fetch

from pg_stat_user_indexes where

indexrelname in (select indexname from pg_indexes where schemaname ='public' and tablename='testdata');

schemaname | relname  |  indexrelname   | index_size | idx_scan | idx_tup_read | idx_tup_fetch

------------+----------+-----------------+------------+----------+--------------+---------------

 public     | testdata | testdata_id_idx |      16384 |        0 |            0 |             0

(1 row)

 

 

这样就完成了主键索引的重建,对于大规模的数据库集群,能够经过 pg_repack 工具进行定时的索引重建。

相关文章
相关标签/搜索