Clickhouse刪除/更新數據(UPDATE/DELETE/DROP)與普通的sql語法有點不一樣,因此做一下記錄。
1 數據刪除
按分區刪除
ALTER TABLE db_name.table_name DROP PARTITION '20200601'
按條件刪除
ALTER TABLE db_name.table_name DELETE WHERE day = '20200618'
2 數據更新
ALTER TABLE <table_name> UPDATE col1 = expr1, ... WHERE <filter>
注意:
1. 該命令必須在版本號大於1.1.54388纔可以使用,適用於 mergeTree 引擎2. 該命令是異步執行的,可以通過查看錶 system.mutations 來查看命令的是否執行完畢
舉例:
:) select event_status_key, count(*) from test_update where event_status_key in (0, 22) group by event_status_key;
┌─event_status_key─┬──count()─┐
│ 0 │ 17824710 │
│ 22 │ 1701 │
└──────────────────┴──────────┘
:) ALTER TABLE test_update UPDATE event_status_key=0 where event_status_key=22;
0 rows in set. Elapsed: 0.067 sec.
:) select event_status_key, count(*) from test_update where event_status_key in (0, 22) group by event_status_key;
┌─event_status_key─┬──count()─┐
│ 0 │ 17826411 │
└──────────────────┴──────────┘
3 Clickhouse更新操作有一些限制:
① 索引列不能進行更新
:) ALTER TABLE test_update UPDATE event_key = 41 WHERE event_key = 40;
Received exception from server (version 18.12.17):
Code: 420. DB::Exception: Received from localhost:9000, ::1. DB::Exception: Cannot UPDATE key column `event_key`.
② 分佈式表不能進行更新
Received exception from server (version 18.12.17):
Code: 48. DB::Exception: Received from localhost:9000, ::1. DB::Exception: Mutations are not supported by storage Distributed.
ALTER TABLE UPDATE/DELETE不支持分佈式DDL,因此需要在分佈式環境中手動在每個節點上local的進行更新/刪除數據。
③ 不適合頻繁更新或point更新
由於Clickhouse更新操作非常耗資源,如果頻繁的進行更新操作,可能會弄崩集羣,請謹慎操作。
參考:
https://www.altinity.com/blog/2018/10/16/updates-in-clickhouse