暂无图片
暂无图片
4
暂无图片
暂无图片
1
暂无图片

PostgreSQL-乱序插入数据导致索引膨胀

原创 ysl 2021-07-17
1087

在对索引进行重建的时候,发现索引比原来更小。
针对这个现象,进行了如下测试:
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)
复制

现象:顺序写入时,索引大小和后建索引大小一致,没有出现膨胀。数据乱序写入时,索引明显占用更大的空间。
结论:索引页里的数据是有序的,索引字段乱序写入,导致索引频繁分裂,使得索引页没有被完全被占用。最终导致索引膨胀。
处理方法:重建索引。

「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
1人已赞赏
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论

冷狼
暂无图片
3月前
评论
暂无图片 0
PostgreSQL-乱序插入数据导致索引膨胀
3月前
暂无图片 点赞
评论