ITPub博客

首页 > 数据库 > PostgreSQL > PostgreSQL-乱序插入数据导致索引膨胀

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

原创 PostgreSQL 作者:T1YSL 时间:2021-07-17 22:33:06 0 删除 编辑

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

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


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/69990629/viewspace-2781886/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论
中国开源软件推进联盟PG分会系列技术丛书《快速掌握PostgreSQL版本新特性》一书副主编。数据库技术专家。数据库认证讲师、恩墨学院数据库讲师。擅长MySQL数据库、PostgreSQL等开源数据库。拥有MySQL-OCP 、PostgreSQL-PGCM等数据库认证。

注册时间:2020-12-12

  • 博文量
    152
  • 访问量
    160792