数据库性能之旅(二)Create Index并行

30 阅读2分钟

并行

通过并行可以做到优化

PostgreSQL

PostgreSQL 11中也引入了并行创建索引

索引创建的阶段

阶段描述
   initializing create index或reindex准备阶段,通常很短。
 ****  waiting for writers before build concurrent   模式特有阶段,CREATE INDEX CONCURRENTLY或REINDEX CONCURRENTLY等待表相关事务完成 
   building index 索引数据构建阶段,相对耗时较多的阶段。
 ****  waiting for writers before validation concurrent   模式特有阶段,CREATE INDEX CONCURRENTLY或REINDEX CONCURRENTLY等待表相关事务完成 
   index validation: scanning index concurrent   模式特有阶段,CREATE INDEX CONCURRENTLY索引数据验证阶段 
   index validation: sorting tuples concurrent   模式特有阶段,CREATE INDEX CONCURRENTLY数据排序阶段 
   index validation: scanning table concurrent   模式特有阶段,CREATE INDEX CONCURRENTLY表数据扫描阶段 
   waiting for old snapshots concurrent   模式特有阶段,CREATE INDEX CONCURRENTLY或REINDEX CONCURRENTLY 等待获取旧快照,这个阶段会创建新快照,并把所有创建过程中的差异数据补齐。
   waiting for readers before marking dead concurrent   模式特有阶段,REINDEX CONCURRENTLY等待表上的读锁释放 
   waiting for readers before dropping concurrent   模式特有阶段,REINDEX CONCURRENTLY等待表上的读锁释放 

可以看到在线(concurrent)创建索引会多做很多额外动作,尽可能保障业务在线运行,要额外花费。

参考链接:

 www.postgresql.org/docs/curren…

这里加入一个 ****Hans-Jürgen Schönig 做过的测试结论,原文见文章末尾:

测试案例:

test=# \d+

 List of relations

 Schema | Name   | Type  | Owner | Size  | Description

--------+--------+-------+-------+-------+-------------

 public | t_demo | table | hs    | 21 GB |

(1 row)

数据量:50亿

CPU:Intel(R) Core(TM) i5-4460 CPU @ 3.20GHz

测试项时间
****不开并行:CREATE INDEX idx1 ON t_demo (data);1031650.658 ms (17:11.651)
****2个并行:CREATE INDEX idx2 ON t_demo (data);660672.867 ms (11:00.673)
****4个并行:CREATE INDEX idx3 ON t_demo (data);534775.040 ms (08:54.775)
增加内存:SET maintenance_work_mem TO '4 GB';CREATE INDEX idx4 ON t_demo (data);448498.535 ms (07:28.499)
优化IO、更换高性能磁盘SSD,把排序磁盘和数据磁盘分开:SET temp_tablespaces TO sortspace;SETCREATE INDEX idx6 ON t_demo (data) TABLESPACE indexspace;checkpoint_timeout = 120minmax_wal_size = 50GBmin_wal_size = 80MB408508.976 ms (06:48.509)

Oracle

CREATE INDEX ... PARALLEL

Polardb

PolarDB PostgreSQL版在执行索引构建时,会首先扫描待构建索引的基表构造出索引项,然后再进一步的根据索引项完成整棵索引树的构建过程。

当使用跨机并行查询功能加速Btree索引构建时,系统会自动构建出一个QC进程完成对基表项的并行扫描,并由索引构建进程接收QC进程扫描结果完成后续的索引创建逻辑。

image.png 参考链接:

 help.aliyun.com/zh/polardb/…

 www.cybertec-postgresql.com/en/postgres…

 wiki.postgresql.org/wiki/Parall…

 www.postgresql.org/docs/curren…

 wiki.postgresql.org/wiki/Parall…