PostgreSQL创建索引对比测试:常规和添加concurrently参数。
测试过程:
创建⼀张测试表:
CREATE TABLE testtab01(id int primary key, note int);
插⼊测试数据:
INSERT INTO testtab01 select generate_series(1,50000000), generate_series(1,50000000); –数据量大一些,否则测不出效果
测试案例一:
这时开两个psql窗⼝,在其中⼀个窗⼝中建索引
⼀个窗⼝:
CREATE INDEX idx_testtab01_note on testtab01(note);
test_db=# CREATE INDEX idx_testtab01_note on testtab01(note);
CREATE INDEX
Time: 24180.121 ms (00:24.180)
另⼀个窗⼝:
DELETE FROM testtab01 where id=8;【先卡住了,待创建完索引后,数据删除成功】
卡住:
test_db=# DELETE FROM testtab01 where id=8;
DELETE 1
Time: 24192.128 ms (00:24.192)
创建索引用了24秒。用时相对短一些
有没有不阻塞dml的加索引⽅式?
PostgreSQL支持在不⻓时间阻塞更新的情况下建⽴创建索引,在CREATE INDEX中加CONCURRENTLY选项。
优点:加索引过程中不会阻塞dml语句
缺点:由于要两次扫描表,所以耗时会⻓⼀些
测试案例二:
其中⼀个窗口加索引
DROP INDEX idx_testtab01_note;
CREATE INDEX CONCURRENTLY idx_testtab01_note on testtab01(note);
test_db=# CREATE INDEX CONCURRENTLY idx_testtab01_note on testtab01(note);
CREATE INDEX
Time: 51300.086 ms (00:51.300)
创建索引用了51秒。用时相对长一些
另⼀个窗⼝的删除语句执⾏
DELETE FROM testtab01 where id=6;
DELETE FROM testtab01 where id=7;
test_db=# DELETE FROM testtab01 where id=7;
DELETE 1
Time: 5720.149 ms (00:05.720)
总结:
1、常规方式创建索引,会锁表,阻塞dml语句。索引创建完成后,即可执行dml语句。创建索引用时相对短一些。【案例1】
2、添加concurrently参数创建索引,不会阻塞dml语句。但是创建索引用时相对长一些。【案例2】