2023年11月26日发(作者:)

clickhouse⾃定义分区及底层存储合并机制

⾃定义分区键

分区是在建表时使⽤PARTITION BY expr ⾃居指定。

分区键可以是表列中的任何表达式。

例如,按⽉指定分区:PARTITION BY toYYYYMM(date_column).使⽤元组指定分区:PARTITION

BY(toMondat(StartDate),EventType)

在将新数据插⼊表中时,每个分区的数据存储为单独的数据⽚段(每个数据⽚段的数据是按逐渐排序的),在插⼊后的10~15分钟内,同

⼀个分区的数据⽚段将合并为⼀个整体的数据⽚段。

分区⽬录的命名规则

根据分区表达式的数据类型,分区的命名规则是存在差异的。

不指定分区:分区名称为all。

数值数据类型:分区名称为数值。

⽇期数据类型:将⽇期装换为数字作为分区名称。

字符串数据类型:将⽇期转换为hash作为分区名称。

系统表:

SELECT partition,name,table,active FROM system.parts WHERE table like 'xxx';

创建不同分区案例

#1.

不指定分区

drop table test_partition_non;

create table test_partition_non(name String, timestamp DateTime) ENGINE=MergeTree() order by name;

insert into test_partition_non values ('nanjing', '2020-04-21 12:23:33');

#2.

数值

drop table test_partition_numeric;

create table test_partition_numeric(id UInt64, timestamp DateTime) ENGINE=MergeTree() order by id partition by id;

insert into test_partition_numeric values (556, '2020-04-21 12:23:33');

#3.

⽇期

drop table test_partition_date;

create table test_partition_date(date Date, timestamp DateTime) ENGINE=MergeTree() order by date partition by date;

insert into test_partition_date values ('2020-04-21', '2020-04-21 12:23:33');

#4.

字符串

drop table test_partition_string;

create table test_partition_string(name String, timestamp DateTime) ENGINE=MergeTree() order by name partition by name;

insert into test_partition_string values ('hangzhou', '2020-04-21 12:23:33');

#

查看表:

SELECT partition, name, table, active FROM system.parts WHERE table like 'test_partition_%';

分区⽬录的合并过程

在将新数据插⼊表中时,每个分区的数据按照⽬录存储为单独的数据⽚段,⽬录名为数据⽚段抿成,这个和表的name字段⼀

致。

在插⼊后的10~15分钟内,同⼀个分区的数据⽚段将合并为⼀个整体的数据⽚段。

数据⽚段名称包含了4部分的信息,下⾯以数据⽚段20200421_1_2_1为例进⾏拆解:

20200421是分区名称

1是数据块的最⼩编号。

2是数据块的最⼤编号。

1是块级别,即该块在MergeTree中的深度。

分区⽬录的合并过程