在对索引进行重建的时候,发现索引比原来更小。
针对这个现象,进行了如下测试:
1.数据库版本为PostgreSQL12.1
[postgres@ysla ~]$ postgres --version postgres (PostgreSQL) 12.1
复制
2.先建表t1_ysl和索引ind_l,之后按乱序插入数值
postgres=# create table t1_ysl(id int); CREATE TABLE postgres=# create index ind_l on t1_ysl(id); CREATE INDEX postgres=# insert into t1_ysl select random()*10000000 from generate_series(1,10000000); INSERT 0 10000000
复制
//插入10000000个1-10000000之间的随机整数
postgres=# \di+ List of relations Schema | Name | Type | Owner | Table | Size | Description --------+-------+-------+----------+--------+--------+------------- public | ind_l | index | postgres | t1_ysl | 284 MB | (1 row)
复制
重建索引后,查看索引大小,索引占用明显下降
postgres=# reindex index ind_l ; REINDEX postgres=# \di+ List of relations Schema | Name | Type | Owner | Table | Size | Description --------+-------+-------+----------+--------+--------+------------- public | ind_l | index | postgres | t1_ysl | 214 MB | (1 row)
复制
3.清除数据,先建立索引,并顺序写入数据
postgres=# truncate t1_ysl ; TRUNCATE TABLE postgres=# \di+ List of relations Schema | Name | Type | Owner | Table | Size | Description --------+-------+-------+----------+--------+------------+------------- public | ind_l | index | postgres | t1_ysl | 8192 bytes | (1 row) postgres=# insert into t1_ysl select generate_series(1,10000000); INSERT 0 10000000
复制
//顺序插入1-10000000的数值
postgres=# \di+ List of relations Schema | Name | Type | Owner | Table | Size | Description --------+-------+-------+----------+--------+--------+------------- public | ind_l | index | postgres | t1_ysl | 214 MB | (1 row)
复制
4.先顺序写入数据,后建立索引
postgres=# create index ind_l on t1_ysl(id); CREATE INDEX postgres=# \di+ List of relations Schema | Name | Type | Owner | Table | Size | Description --------+-------+-------+----------+--------+--------+------------- public | ind_l | index | postgres | t1_ysl | 214 MB | (1 row)
复制
现象:顺序写入时,索引大小和后建索引大小一致,没有出现膨胀。数据乱序写入时,索引明显占用更大的空间。
结论:索引页里的数据是有序的,索引字段乱序写入,导致索引频繁分裂,使得索引页没有被完全被占用。最终导致索引膨胀。
处理方法:重建索引。
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。
评论
PostgreSQL-乱序插入数据导致索引膨胀
3月前

评论
相关阅读
9.9 分高危漏洞,尽快升级到 pgAdmin 4 v9.2 进行修复
严少安
346次阅读
2025-04-11 10:43:23
3月“墨力原创作者计划”获奖名单公布
墨天轮编辑部
326次阅读
2025-04-15 14:48:05
外国CTO也感兴趣的开源数据库项目——openHalo
小满未满、
296次阅读
2025-04-21 16:58:09
openHalo问世,全球首款基于PostgreSQL兼容MySQL协议的国产开源数据库
严少安
289次阅读
2025-04-07 12:14:29
云和恩墨钟浪峰:安全生产系列之SQL优化安全操作
墨天轮编辑部
239次阅读
2025-03-31 11:08:20
postgresql+patroni+etcd高可用安装
necessary
158次阅读
2025-03-28 10:11:23
手把手教你在 openKylin 上部署 IvorySQL 4.4
严少安
150次阅读
2025-03-27 20:41:28
从 Oracle 到 PostgreSQL迁移成本评估揭秘
梧桐
148次阅读
2025-03-27 17:21:42
转发有奖 | PostgreSQL 16 PGCM高级认证课程直播班招生中!
墨天轮小教习
142次阅读
2025-04-14 15:58:34
墨天轮PostgreSQL认证证书快递已发(2025年3月批)
墨天轮小教习
125次阅读
2025-04-03 11:43:25