Hash 索引创建奇慢

今天学习了下 Hash 索引,在了解HASH索引的应用场合后,打算实践一下,但在创建过程中奇慢,有个测试表才 1.5G 大,在创建了两小时候还没结束,而且系统上也没有锁。于是猜测 HASH 索引创建应该比 btree 索引创建慢得多,下面是做的一些测试,用来比较不同数据量环境下创建 btree 索引和 HASH 索引的速度。

机器配置

8 CPU 8G 内存
OS Red Hat Enterprise Linux Server release 5.5

场景一:创建表test_a, 插入1000条数据

1
2
3
4
5
6
7
8
9
10
skytf=> create table test_a (id integer,name varchar(32));  
CREATE TABLE
skytf=> insert into test_a select generate_series(1,1000),'francs';
INSERT 0 1000
skytf=> create index idx_btree_test_a_name on test_a using btree (name);
CREATE INDEX
Time: 35.931 ms
skytf=> create index idx_hash_test_a_name on test_a using hash (name);
CREATE INDEX
Time: 2.578 ms

在 1000条数据下,创建 btree索引花了 35.9 ms , 创建 hash索引花了2.6ms

场景二:创建表 test_b, 插入1万条数据

1
2
3
4
5
6
7
8
9
10
skytf=> create table test_b (id integer,name varchar(32));  
CREATE TABLE
skytf=> insert into test_a select generate_series(1,10000),'francs';
INSERT 0 10000
skytf=> create index idx_btree_test_b_name on test_b using btree (name);
CREATE INDEX
Time: 56.990 ms
skytf=> create index idx_hash_test_b_name on test_b using hash (name);
CREATE INDEX
Time: 56.261 ms

在 1万 条数据下,创建 btree索引花了 56.9ms , 创建 hash索引花了 56.2 ms

场景三:创建表 test_c, 插入10万条数据

1
2
3
4
5
6
7
8
9
10
skytf=> create table test_c (id integer,name varchar(32));  
CREATE TABLE
skytf=> insert into test_a select generate_series(1,100000),'francs';
INSERT 0 100000
skytf=> create index idx_btree_test_c_name on test_c using btree (name);
CREATE INDEX
Time: 181.033 ms
skytf=> create index idx_hash_test_c_name on test_c using hash (name);
CREATE INDEX
Time: 4643.801 ms

在 10万 条数据下,创建 btree索引花了 181.0 ms , 创建 hash索引花了 4643 ms

场景四:创建表 test_d, 插入100万条数据

1
2
3
4
5
6
7
8
9
10
skytf=> create table test_d (id integer,name varchar(32));  
CREATE TABLE
skytf=> insert into test_d select generate_series(1,1000000),'francs';
INSERT 0 1000000
skytf=> create index idx_btree_test_d_name on test_d using btree (name);
CREATE INDEX
Time: 1909.001 ms
skytf=> create index idx_hash_test_d_name on test_d using hash (name);
CREATE INDEX
Time: 591817.814 ms

在 100万 条数据下,创建 btree索引花了 1909.0 ms , 创建 hash索引花了 591817 ms 在这种情况下,创建HASH索引明显很慢,创建HASH索引的时间是创建btree 索引的近 31倍。

四种场景时间统计

表名记录数创建 Btree 索引耗时(ms)创建 Hash 索引耗时 (ms)
table_a100035.92.6
table_b1万56.956.2
table_c10万1814643
table_d100万1909591817

总结

  1. 因为 hash 索引创建消耗的时间很长,可以预计当表达到 1G 以上,创建 HASH 索引
    将会变得非常艰难,保守估计,创建 hash 索引花费的时间至少是 创建btree 所花费
    的时间 20 倍以上。

  2. 尽管 Hash 索引适用于特定场合,但创建很慢,推测创建 HASH索引后,此索引维护
    代价(指删入操作)非常大,所以不建议使用到生产库中。

  3. 至于在特定场合 Hash 索引是否比 btree 索引高效,还有侍验证。

原创文章,作者:carmelaweatherly,如若转载,请注明出处:https://blog.ytso.com/236368.html

(0)
上一篇 2022年1月24日
下一篇 2022年1月24日

相关推荐

发表回复

登录后才能评论