pg_repack
PostgreSQL通过数据多版本实现MVCC,删除数据并不会真正删除数据,而是修改标识。更新是通过删除+插入的方式进行。所以在频繁更新的系统,如果不进行处理,数据膨胀倍数可能达到十几倍。
PostgreSQL数据库支持通过插件pg_repack在线清理表空间,有可处理对表大量更新等操作导致的表膨胀问题,pg_repack无需获取排它锁,相比CLUSTER或VACUUM FULL更加轻量化。
pg_repack是一个可以在线重建表和索引的扩展,它会在数据库中创建一个和需要清理的目标表一样的临时表,将目标表中的数据COPY到临时表并在临时表上建立和目标表一样的索引,然后通过重命名的方式用临时表替换目标表。
安装
进入相应目录
make && make install
create extension pg_repack;
create extension pgstattuple;
在线pg_repack
repack数据库
pg_repack -p 5432 -d #### --no-order --jobs 4 --elevel=info
repack模式
pg_repack -p 5432 -d kingdee --schema=public --no-order --jobs 4 --elevel=info
repack表和索引
pg_repack -p 5432 -d kingdee --no-order --table public.large_test --elevel=info
repack所有索引
pg_repack -p 5432 -d kingdee --no-order --only-indexes --table public.large_test --elevel=info
repack指定索引
pg_repack -p 5432 -d kingdee --index public.large_test_pkey --elevel=info
pg_repack注意事项
pg_repack需要额外的存储空间。全表repack时,剩余存储空间大小需要至少是待repack表大小的2倍。
pg_repack无法操作临时表。
pg_repack无法操作GiST索引。
pg_repack运行时无法对repack操作中的表执行DDL。pg_repack会持有ACCESS SHARE锁,禁止DDL执行。
参数--dry-run检测哪些表支持pg_repack
$ pg_repack --dry-run -d percona --table scott.employee
INFO: Dry run enabled, not executing repack
INFO: repacking table "scott.employee"
如果不支持,会提示:
$ pg_repack --dry-run -d percona --table scott.sales
INFO: Dry run enabled, not executing repack
WARNING: relation "scott.sales" must have a primary key or not-null unique keys