例如脚本: cat pg_engine_vacuum.sh #!/bin/bash #2014-10-22 tina date=`date +"%Y-%m-%d %H:%M:%S"` echo "begin time is: $date" >>/tmp/pg_tinadb_vacuum.log
tables=$(psql -U postgres -d tinadb -c "select tablename from pg_tables where schemaname='public';" |grep -v "tablename") echo $tables >>/tmp/pg_tinadb_vacuum.log
for table in $tables do psql -U postgres -d tinadb -c "vacuum full $table;" >>/tmp/pg_tinadb_vacuum.log echo "table $table has finished vacuum.">>/tmp/pg_tinadb_vacuum.log done
添加到crontab 定时执行即可。
3)命令设置某个表不进行autovacuum: tina=# alter table test1 set (autovacuum_enabled=false); ALTER TABLE tina=# select relname from pg_class where reloptions@>array['autovacuum_enabled=false']; relname --------- test1 (1 row)
三、reindex reindex命令: REINDEX { INDEX | TABLE | DATABASE | SYSTEM } name [ FORCE ]
postgres=# reindex database tina; ERROR: can only reindex the currently open database postgres=# \c tina You are now connected to database "tina" as user "postgres". tina=# reindex database tina; NOTICE: table "pg_catalog.pg_class" was reindexed NOTICE: table "pg_catalog.pg_statistic" was reindexed .... 会将当前open的tina库里的索引都重建
reindx table tablename; 会将表中的所有索引都重建
reindex index indexname; 会将指定的这一个索引重建
索引原大小: SELECT relname, pg_relation_size(oid)/1024 || 'K' AS size FROM pg_class WHERE relkind='i' and relname='t_cert_sample_state_idx'; relname | size -------------------------+--------- t_cert_sample_state_idx | 106000K (1 row)
重建索引: REINDEX INDEX t_cert_sample_state_idx; REINDEX
重建后索引大小: SELECT relname, pg_relation_size(oid)/1024 || 'K' AS size FROM pg_class WHERE relkind='i' and relname='t_cert_sample_state_idx'; relname | size -------------------------+-------- t_cert_sample_state_idx | 94648K (1 row)
索引重建后一定要分析表: ANALYZE t_cert; ANALYZE
补充: 1. 查看表所占用的磁盘页面数 SELECT relfilenode, relpages FROM pg_class WHERE relname = 't_cert'; relfilenode | relpages -------------+---------- 49037978 | 384895 (1 row) 说明:relpages只能被VACUUM、ANALYZE和几个DDL命令更新,如CREATE INDEX。通常一个页面的长度为8K字节。 2. 查看表的索引名和索引占用的磁盘页面数量。 SELECT c2.relname, c2.relpages FROM pg_class c, pg_class c2, pg_index i WHERE c.relname = 't_cert' AND c.oid = i.indrelid AND c2.oid = i.indexrelid ORDER BY c2.relname; relname | relpages ----------------------------------+---------- sign_android_pkey | 11659 t_cert_sample_state_idx | 11831 t_cert_serialnumber_hash_md5_key | 45887 (3 rows)