Postgresql表膨胀率计算
一、简介
PostgreSQL自带了pgstattuple模块,可用于精确计算表的膨胀率。譬如这里的tuple_percent字段就是元组实际字节占关系总大小的百分比,用1减去该值即为膨胀率。

二、示例一
#插入1000W数据
postgres=# insert into t select id,id from generate_series(1,10000000) as id;INSERT 0 10000000 #表膨胀系数为0.097postgres=# select *, 1.0 - tuple_len::numeric / table_len as bloat from pgstattuple('t'); table_len | tuple_count | tuple_len | tuple_percent | dead_tuple_count | dead_tuple_len | dead_tuple_percent | free_space | free_percent | bloat -----------+-------------+-----------+---------------+------------------+----------------+--------------------+------------+--------------+------------------------ 442818560 | 10000001 | 400000040 | 90.33 | 0 | 0 | 0 | 1304976 | 0.29 | 0.09669540499838127833(1 row) #占用54055个pagepostgres=# select * from pg_relpages('t'); pg_relpages ------------- 54055(1 row) #删除数据postgres=# delete from t where id<>10000000;DELETE 9999999 #仍然占用54055个pagepostgres=# select * from pg_relpages('t'); pg_relpages ------------- 54055(1 row) #膨胀率已经为0.999999postgres=# select *, 1.0 - tuple_len::numeric / table_len as bloat from pgstattuple('t'); table_len | tuple_count | tuple_len | tuple_percent | dead_tuple_count | dead_tuple_len | dead_tuple_percent | free_space | free_percent | bloat -----------+-------------+-----------+---------------+------------------+----------------+--------------------+------------+--------------+---------------------------- 442818560 | 2 | 80 | 0 | 9999999 | 399999960 | 90.33 | 1304976 | 0.29 | 0.999999819339099065766349 #vacuum表postgres=# vacuum (verbose,full,analyze) t;INFO: vacuuming "public.t"INFO: "t": found 5372225 removable, 2 nonremovable row versions in 54055 pagesDETAIL: 0 dead row versions cannot be removed yet.CPU: user: 0.89 s, system: 0.00 s, elapsed: 0.89 s.INFO: analyzing "public.t"INFO: "t": scanned 1 of 1 pages, containing 2 live rows and 0 dead rows; 2 rows in sample, 2 estimated total rowsVACUUM三、示例二
pg索引膨胀问题---重建索引
\di+ 索引名查看索引大小
发现数据库中很多表的索引大小超过数据大小。由于频繁更新就会带来索引膨胀。
对于大的索引可以采用重建的方式解决。以下两种方法推荐第一种。
方法一:停止应用(这个操作会锁表),重建索引(注:重建完索引名称不变)
sql:reindex index 索引名称
reindex table 表名
方法二:在线建新索引,再把旧索引删除
知识分享,需人人参与,看完请点赞留言,共同讨论进步

浙公网安备 33010602011771号