【Clickhouse】Clickhouse TTL 数据的存活时间

在这里插入图片描述

1.概述

转载:Clickhouse TTL

2.环境

运行环境:

centos 7.6
Clickhouse> select version();
 
SELECT version()
 
┌─version()─┐
│ 20.4.4.18 │
└───────────┘

TTL即Time To Live 表示数据的存活时间。在MergeTree中,可以为某个列字段或者整张表设置TTL当时间达到时,若列字段级别的TTL 则会删除这一列的数据;若表级别的TTL则会删除整张表的数据;若同时设置了列级别的和表级别的TTL则以先到期的为准

无论列级别还是表级别的TTL,都需要依托某个Datetime或者date类型的字段,通过对这个时间字段的INTERVAL操作来表述TTL的过期时间:

示例:

TTL time_column + interval 3 DAY

表示数据存活的时间为time_column 时间的3天之后。

INTERVAL支持的操作:second,minute,hour,day,week,month,quarter,year。

3.适用场景

数仓建设需要考虑数据的生命周期问题,数据的生命周期包括数据最初的写入,存储,处理,查询,归档和销毁几个基本的阶段。
实际中数仓数据量的成倍增长,不但产生了巨大容量的存储,同时也造成管理的困难,更换存储方式和存储迁移对项目来讲都是需要考虑
成本和风险的。clickhouse这样的一个设计,可以有效处理解决数据有效的存储周期和销毁的问题。ck的出现对数据存储的数仓的业务选型又添加一种选择。

概言之:

  1. 定期删除过期数据
  2. 定期移动过期数据进行归档

适用对象:

1.2.3.分区表
4.物化视图的列

4.列级别的TTL

若要设置列级别的TTL,则需要在定义表字段的时候,为他们声明TTL表达式,主键字段不能被声明TTL。

Clickhouse> create table t_column_ttl(id UInt64 comment 'Primary key'
,create_time Datetime
,product_desc String  TTL create_time + interval 10 second
,product_type UInt8 TTL create_time + interval 10 second) 
engine=MergeTree partition by toYYYYMM(create_time) order by id;
 
 
CREATE TABLE t_column_ttl
(
    `id` UInt64 COMMENT 'Primary key', 
    `create_time` Datetime, 
    `product_desc` String TTL create_time + toIntervalSecond(10), 
    `product_type` UInt8 TTL create_time + toIntervalSecond(10)
)
ENGINE = MergeTree
PARTITION BY toYYYYMM(create_time)
ORDER BY id
 
Ok.
 
0 rows in set. Elapsed: 0.059 sec. 
 
Clickhouse> insert into table t_column_ttl values(1,now(),'Huawei',1),(2,now()+interval 1 minute,'Apple',2);
 
INSERT INTO t_column_ttl VALUES
 
Ok.
 
2 rows in set. Elapsed: 0.018 sec. 
 
Clickhouse> select * from t_column_ttl;
 
SELECT *
FROM t_column_ttl
 
┌─id─┬─────────create_time─┬─product_desc─┬─product_type─┐
│  12020-06-15 12:10:20 │ Huawei       │            1 │
│  22020-06-15 12:11:20 │ Apple        │            2 │
└────┴─────────────────────┴──────────────┴──────────────┘
 
2 rows in set. Elapsed: 0.003 sec. 
 
Clickhouse> select sleep(10);
 
SELECT sleep(10)
 
↙ Progress: 0.00 rows, 0.00 B (0.00 rows/s., 0.00 B/s.) Received exception from server (version 20.4.4):
Code: 160. DB::Exception: Received from localhost:9000. DB::Exception: The maximum sleep time is 3 seconds. Requested: 10. 
 
0 rows in set. Elapsed: 0.111 sec. 
 
Clickhouse> select sleep(3);
 
SELECT sleep(3)
 
┌─sleep(3)─┐
│        0 │
└──────────┘
 
1 rows in set. Elapsed: 3.003 sec. 
 
Clickhouse> select * from t_column_ttl;
 
SELECT *
FROM t_column_ttl
 
┌─id─┬─────────create_time─┬─product_desc─┬─product_type─┐
│  12020-06-15 12:10:20 │ Huawei       │            1 │
│  22020-06-15 12:11:20 │ Apple        │            2 │
└────┴─────────────────────┴──────────────┴──────────────┘
 
2 rows in set. Elapsed: 0.002 sec. 
 
Clickhouse> optimize table t_column_ttl final;
 
OPTIMIZE TABLE t_column_ttl FINAL
 
Ok.
 
0 rows in set. Elapsed: 0.004 sec. 
 
Clickhouse> select * from t_column_ttl;
 
SELECT *
FROM t_column_ttl
 
┌─id─┬─────────create_time─┬─product_desc─┬─product_type─┐
│  12020-06-15 12:10:20 │              │            0 │
│  22020-06-15 12:11:20 │              │            0 │
└────┴─────────────────────┴──────────────┴──────────────┘
 
2 rows in set. Elapsed: 0.003 sec. 

执行optimize命令会强制触发TTL清理,若再次查询可以看到满足TTL条件之后,定义了TTL操作的字段列会被还原为数据类型的默认值。

修改列字段的TTL或者修改已有字段的TTL::

Clickhouse> alter table t_column_ttl MODIFY COLUMN product_desc String  TTL create_time + INTERVAL  2 DAY;

添加字段的TTL:

Clickhouse> alter table t_column_ttl add column product_name String comment '产品名称' ttl create_time + interval 3 month;
 

– 查看TTL的信息:

Clickhouse> desc t_column_ttl;
 
DESCRIBE TABLE t_column_ttl
 
┌─name─────────┬─type─────┬─default_type─┬─default_expression─┬─comment─────┬─codec_expression─┬─ttl_expression─────────────────────┐
│ id           │ UInt64   │              │                    │ Primary key │                  │                                    │
│ create_time  │ DateTime │              │                    │             │                  │                                    │
│ product_desc │ String   │              │                    │             │                  │ create_time + toIntervalDay(2)     │
│ product_type │ UInt8    │              │                    │             │                  │ create_time + toIntervalSecond(10) │
│ product_name │ String   │              │                    │ 产品名称    │                  │ create_time + toIntervalMonth(3)   │
└──────────────┴──────────┴──────────────┴────────────────────┴─────────────┴──────────────────┴────────────────────────────────────┘
 
5 rows in set. Elapsed: 0.003 sec. 

6. 表级别的TTL

可以在MergeTree的表参数中增加TTL表达式 为整张表设置TTL。

– 设置之前需要查找配置的 disk和volume:

Clickhouse> select * from system.disks
:-] ;
 
SELECT *
FROM system.disks
 
┌─name─────────┬─path──────────────────────┬──free_space─┬─total_space─┬─keep_free_space─┐
│ default/var/lib/clickhouse/7788174336160956405761024 │
│ disk_archive │ /data/clickhouse_archive/213757952107248353280 │
│ disk_cold    │ /data/clickhouse_cold/213757952107248353280 │
│ disk_hot1    │ /opt/clickhouse_hot1/16288342016268304384000 │
│ disk_hot2    │ /opt/clickhouse_hot2/16288342016268304384000 │
└──────────────┴───────────────────────────┴─────────────┴─────────────┴─────────────────┘
 
5 rows in set. Elapsed: 0.004 sec. 
 
Clickhouse> select * from system.storage_policies;
 
SELECT *
FROM system.storage_policies
 
┌─policy_name──────┬─volume_name─┬─volume_priority─┬─disks─────────────────────┬─max_data_part_size─┬─move_factor─┐
│ JBOD_default     │ disk_group  │               1['disk_hot1','disk_hot2']00.1 │
│ defaultdefault1['default']00 │
│ default_hot_cold │ hot         │               1['disk_hot1','disk_hot2']10485760.2 │
│ default_hot_cold │ cold        │               2['disk_cold']107374182400.2 │
│ default_hot_cold │ archive     │               3['disk_archive']00.2 │
└──────────────────┴─────────────┴─────────────────┴───────────────────────────┴────────────────────┴─────────────┘
 
5 rows in set. Elapsed: 0.006 sec. 
 

表的定义:

create table t_table_ttl(id UInt64 comment '主键',create_time Datetime comment '创建时间',product_desc String  comment '产品描述' TTL create_time + interval 10 minute,product_type UInt8 ) 
engine=MergeTree partition by toYYYYMM(create_time) order by create_time
TTL create_time  + INTERVAL 1 MONTH ,
    create_time + INTERVAL 1 WEEK TO VOLUME 'default',
    create_time + INTERVAL 2 WEEK TO DISK 'default';
 

可以看到t_table_ttl 整张表被设置为TTL,当触发TTL清理的时候,哪些满足过期时间的数据行将会被正行删除。

表级别的TTL修改:

Clickhouse> alter table t_table_ttl modify ttl create_time + interval 2 month;
 

查看信息:

Clickhouse> select database,name,engine,data_paths,metadata_path,metadata_modification_time,partition_key,sorting_key from system.tables where name='t_table_ttl';
 
SELECT 
    database, 
    name, 
    engine, 
    data_paths, 
    metadata_path, 
    metadata_modification_time, 
    partition_key, 
    sorting_key
FROM system.tables
WHERE name = 't_table_ttl'
 
┌─database─┬─name────────┬─engine────┬─data_paths──────────────────────────────────────┬─metadata_path──────────────────────────────────────┬─metadata_modification_time─┬─partition_key─────────┬─sorting_key─┐
│ study    │ t_table_ttl │ MergeTree │ ['/var/lib/clickhouse/data/study/t_table_ttl/']/var/lib/clickhouse/metadata/study/t_table_ttl.sql2020-06-15 13:01:32 │ toYYYYMM(create_time) │ create_time │
└──────────┴─────────────┴───────────┴─────────────────────────────────────────────────┴────────────────────────────────────────────────────┴────────────────────────────┴───────────────────────┴─────────────┘
 
1 rows in set. Elapsed: 0.010 sec. 
 

查看表的结构:

Clickhouse> desc t_table_ttl;
 
DESCRIBE TABLE t_table_ttl
 
┌─name─────────┬─type─────┬─default_type─┬─default_expression─┬─comment──┬─codec_expression─┬─ttl_expression─────────────────────┐
│ id           │ UInt64   │              │                    │ 主键     │                  │                                    │
│ create_time  │ DateTime │              │                    │ 创建时间 │                  │                                    │
│ product_desc │ String   │              │                    │ 产品描述 │                  │ create_time + toIntervalMinute(10) │
│ product_type │ UInt8    │              │                    │          │                  │                                    │
└──────────────┴──────────┴──────────────┴────────────────────┴──────────┴──────────────────┴────────────────────────────────────┘
 
4 rows in set. Elapsed: 0.002 sec. 

注意:列级别或者表级别的TTL 目前暂不支持取消操作

7.TTL的运行原理

若一张MergeTree表被设置为TTL 则在写入数据时候会以数据分区为单位,在每个分区目录内生成一个ttl.txt的文件。

写入数据:

Clickhouse> insert into t_table_ttl(id,create_time,product_desc,product_type)values(10,now(),'Huawei',1),(20,now()+ interval 10 minute,'Apple',2);
 
 
[root@hadoop101 ~]# ls -l /var/lib/clickhouse/data/study/t_table_ttl/202006_1_1_0/
total 60
-rw-r----- 1 clickhouse clickhouse 465 Jun 15 13:14 checksums.txt
-rw-r----- 1 clickhouse clickhouse 115 Jun 15 13:14 columns.txt
-rw-r----- 1 clickhouse clickhouse   1 Jun 15 13:14 count.txt
-rw-r----- 1 clickhouse clickhouse  34 Jun 15 13:14 create_time.bin
-rw-r----- 1 clickhouse clickhouse  48 Jun 15 13:14 create_time.mrk2
-rw-r----- 1 clickhouse clickhouse  39 Jun 15 13:14 id.bin
-rw-r----- 1 clickhouse clickhouse  48 Jun 15 13:14 id.mrk2
-rw-r----- 1 clickhouse clickhouse   8 Jun 15 13:14 minmax_create_time.idx
-rw-r----- 1 clickhouse clickhouse   4 Jun 15 13:14 partition.dat
-rw-r----- 1 clickhouse clickhouse   8 Jun 15 13:14 primary.idx
-rw-r----- 1 clickhouse clickhouse  39 Jun 15 13:14 product_desc.bin
-rw-r----- 1 clickhouse clickhouse  48 Jun 15 13:14 product_desc.mrk2
-rw-r----- 1 clickhouse clickhouse  28 Jun 15 13:14 product_type.bin
-rw-r----- 1 clickhouse clickhouse  48 Jun 15 13:14 product_type.mrk2
-rw-r----- 1 clickhouse clickhouse 137 Jun 15 13:14 ttl.txt
 
可以看到在分区目录下有ttl.txt 文件,文件的内容为:
# cat ttl.txt 
ttl format version: 1
{
   
   "columns":[{
   
   "name":"product_desc","min":1592198679,"max":1592199279}],"table":{
   
   "min":1597468479,"max":1597469079}}

可以看到MergeTree是通过一串JSON配置保存了TTL的相关信息。
columns 用于保存列级别的TTL信息

  1. tables 用于保存表级别的TTL信息
  2. min和max则保存了当前数据分区内TTL指定的日期字段的最小值和最大值分别与INTERVAL表达式计算后的时间戳。
Clickhouse> select now();
 
SELECT now()
 
┌───────────────now()─┐
│ 2020-06-15 13:28:02 │
└─────────────────────┘
 
1 rows in set. Elapsed: 0.004 sec. 

列的:

Clickhouse> select toDateTime('1592198679') ttl_min,toDateTime('1592199279') ttl_max,ttl_min - min(create_time) expire_min,ttl_max - max(create_time) expire_max from t_table_ttl;
 
SELECT 
    toDateTime('1592198679') AS ttl_min, 
    toDateTime('1592199279') AS ttl_max, 
    ttl_min - min(create_time) AS expire_min, 
    ttl_max - max(create_time) AS expire_max
FROM t_table_ttl
 
┌─────────────ttl_min─┬─────────────ttl_max─┬─expire_min─┬─expire_max─┐
│ 2020-06-15 13:24:392020-06-15 13:34:39600600 │
└─────────────────────┴─────────────────────┴────────────┴────────────┘
 
1 rows in set. Elapsed: 0.026 sec. 
 

表值:

Clickhouse> select toDateTime('1597468479') ttl_min,toDateTime('1597469079') ttl_max,ttl_min - min(create_time) expire_min,ttl_max - max(create_time) expire_max from t_table_ttl;
 
SELECT 
    toDateTime('1597468479') AS ttl_min, 
    toDateTime('1597469079') AS ttl_max, 
    ttl_min - min(create_time) AS expire_min, 
    ttl_max - max(create_time) AS expire_max
FROM t_table_ttl
 
┌─────────────ttl_min─┬─────────────ttl_max─┬─expire_min─┬─expire_max─┐
│ 2020-08-15 13:14:392020-08-15 13:24:3952704005270400 │
└─────────────────────┴─────────────────────┴────────────┴────────────┘
 
1 rows in set. Elapsed: 0.006 sec. 
 

可以看ttl.txt 记录的极值区间恰好等于当前数据分区内create_time的最大值和最小值,和TTL的表达式的预期相符合。

通过TTL的信息记录方式 可以推断大体的处理逻辑:

  1. MergeTree 是以分区目录为单位,通过ttl.txt 记录过期时间,并以此作为判断标准。
  2. 每当写入一批数据时候,都会基于interval 表达式的计算结果为这个分区生成ttl.txt 文件
  3. 只有在MergeTree合并分区才会触发TTL过期数据的逻辑
  4. 在删除分区的时候,选择使用了贪婪算法,算法规则即尽可能找到会最早过期,同时时间最早的分区。
  5. 若一个分区内某一列因为TTL到期则全部删除,在合并之后生成的新分区目录中将不会包含这个列字段的数据文件(.bin 和.mrk)

注意

  1. TTL默认的合并频率有MergeTree的参数merge_with_ttl_timeout 控制,默认周期未86400秒。
    它专门维护一个专有的TTL任务队列。有别于MergeTree的常规合并任务,若这个值设置的过小则可能会带来性能损耗。
    此设置意味着仅在一个分区上或发生后台合并时,每24小时执行一次TTL删除。因此,在最坏的情况下,ClickHouse现在最多每24小时删除一个与TTL delete表达式匹配的分区。
    此行为可能并不理想,因此,如果您希望TTL删除表达式更快地执行删除操作,则可以修改表的merge_with_ttl_timeout设置
alter table t_table_ttl  MODIFY SETTING merge_with_ttl_timeout = 3600;

设置为一个小时。

  1. 除了触发TTL合并外,optimize 命令可以强制触发合并。
触发一个分区合并:
optimize table t;
触发所有分区合并:
optimize table t final;
  1. 目前没有删除ttl的声明方法,但是提供了全局控制TTL合并任务的启动和关停方法:
system stop/start TTL MERGE

相关参数:

以下是参数及其当前默认值的列表:

background_move_pool_size:8
background_move_processing_pool_thread_sleep_seconds:10
background_move_processing_pool_thread_sleep_seconds_random_part:1.0
background_move_processing_pool_thread_sleep_seconds_if_nothing_to_do:0.1
background_move_processing_pool_task_sleep_seconds_when_no_work_min:10
background_move_processing_pool_task_sleep_seconds_when_no_work_max:600
background_move_processing_pool_task_sleep_seconds_when_no_work_multiplier:1.1
background_move_processing_pool_task_sleep_seconds_when_no_work_random_part:1.0

猜你喜欢

转载自blog.csdn.net/qq_21383435/article/details/113531930