说明
clickhourse 是 OLAP 数据库,不支持 delete、update 操作,但可以通过 Mutation 方式实现
有以下缺点:
- 是 很重 的操作,因为每次 delete、update,都会导致 重新分区
- 不支持事务,一旦语句被提交执行,就会立刻对现有数据产生影响,无法回滚;
- Mutation语句的执行是一个异步的后台过程,语句被提交之后就会立即返回成功,但是,当数据量大时,不会立即执行,即:立即查询,数据仍然存在。
提示:由于一般测试的数据很少,
DELETE操作给人的感觉是立即执行的
应用场景
适合批量操作,不适合 频繁、少量数据 操作
删除数据 delete
语法
alter table 表名 delete where 列名 = 值
例子
建表:
create table t_order_del(
id UInt32 COMMENT '主键',
sn String COMMENT '订单编号',
total Decimal(11,2) COMMENT '总金额',
create_time Datetime COMMENT '创建时间'
)
engine=ReplacingMergeTree(create_time)
partition by toYYYYMMDD(create_time)
primary key(id)
order by (id, sn);
插入数据:
insert into t_order_del values
(1,'0001',100,'2022-01-01 11:20:00'),
(2,'0002',200,'2022-01-02 11:30:00'),
(3,'0003',300,'2022-01-03 10:00:00'),
查看文件
cd /program/clickhouse/data/data/default/t_order_del
ll
文件列表如下:
20220101_1_1_0
20220102_2_2_0
20220103_3_3_0
detached
format_version.txt
正常的分区目录
删除数据:
alter table t_order_del delete where id=1
查看文件
ll
显示结果如下:
20220101_1_1_0
20220102_2_2_0
20220102_2_2_0_4
20220103_3_3_0
20220103_3_3_0_4
detached
format_version.txt
mutation_4.txt
多出以下文件:
- 20220102_2_2_0_4
- 20220103_3_3_0_4
- mutation_4.txt
结论
删除操作,会引发重新分区,会影响速度、效率
旧数据 所在的分区 20220101_1_1_0 仍然存在,没有删除
查看 mutation_4.txt 文件
查看文件:mutation_4.txt
内容如下:
format version: 1
create time: 2022-06-02 10:59:15
commands: DELETE WHERE id = 1
旧数据删除时机
- 自动合并分区时
- 手动合并分区
手动合并分区
optimize table t_order_del final;
查看文件
ll
执行结果如下:
20220102_2_2_0_4
20220102_2_2_1_4
20220103_3_3_0_4
20220103_3_3_1_4
detached
format_version.txt
mutation_4.txt
id=1 所在的 20220101_1_1_0 分区被删除了
注意 注意 注意: 执行后,需要等待几分钟才会删除,约 5-8 分钟
修改数据 update
语法
alter table 表名 update 列名 = 新列值 where 列名 = 值
例子
建表:
create table t_order_upd(
id UInt32 COMMENT '主键',
sn String COMMENT '订单编号',
total Decimal(11,2) COMMENT '总金额',
create_time Datetime COMMENT '创建时间'
)
engine=ReplacingMergeTree(create_time)
partition by toYYYYMMDD(create_time)
primary key(id)
order by (id, sn);
插入数据:
insert into t_order_upd values
(1,'0001',100,'2022-01-01 11:20:00'),
(2,'0002',200,'2022-01-02 11:30:00'),
(3,'0003',300,'2022-01-03 10:00:00'),
查看文件
cd /program/clickhouse/data/data/default/t_order_upd
ll
文件列表如下:
20220101_1_1_0
20220102_2_2_0
20220103_3_3_0
detached
format_version.txt
正常的分区目录
修改数据:
alter table t_order_upd update total = 150 where id=1
查看文件
ll
显示结果如下:
20220101_1_1_0
20220101_1_1_0_4
20220102_2_2_0
20220102_2_2_0_4
20220103_3_3_0
20220103_3_3_0_4
detached
format_version.txt
mutation_4.txt
多出以下文件:
- 20220101_1_1_0_4
- 20220102_2_2_0_4
- 20220103_3_3_0_4
- mutation_4.txt:修改是 mutation 操作,会生成
mutation_version.txt文件
结论
修改操作,会引发重新分区,会影响速度、效率
查看 mutation_4.txt 文件
查看文件:mutation_4.txt
内容如下:
format version: 1
create time: 2022-06-02 14:46:46
commands: UPDATE total = 150 WHERE id = 1
使用建议
按照官方的说明,update/delete 的使用场景是一次更新大量数据,也就是where条件筛选的结果应该是一大片数据。
举例:
alter table test update status=1 where status=0 and day='2020-04-01'
一次更新一天的数据。
不建议使用
也可以更新一条数据,但频繁的这种操作,可能会对服务造成压力。
如果只更新一条数据,工作量小,也需要重建分区,效率低下
对于频繁单条更新的这种场景,建议使用 ReplacingMergeTree 引擎来变相解决