Clickhouse数据库迁移
clickhouse官方文档: https://clickhouse.com/docs
1. Clickhouse拉取远程数据库文件
- clickhouse数据存于 {clickhouse_home}/data/{database}/{table}目录下
- 可直接将数据文件复制过来,放在clickhouse_home/data/{database}/${table}/detached/目录下
- 在本地执行alter table {database}.{table} attach [partition ‘partition’]写入数据
以下是获取数据文件的脚本
#!/bin/bash
remote_host=root@192.168.1.1
movefile() {
file_prifix=$1
database=$1
remote_cmd="find /data/clickhouse/data/${database}/*/ -type d -name '$file_prifix*'"
attach_files=$(ssh $remote_host $remote_cmd)
attach_files=($attach_files)
for attach_file in "${attach_files[@]}"; do
if [[ "$attach_file" == *"24h"* ]]; then
continue
fi
detached_file=`getDetachPath $attach_file`
scp -r $remote_host:$attach_file $detached_file
chown -R clickhouse:clickhouse $detached_file
chmod -R 755 $detached_file
done
}
getDetachPath() {
path=$(echo "$1" | sed 's|/*$||')
# 获取目录部分,不包括文件名(如果有的话)
dirname=$(dirname "$path")
# 获取basename,即路径中的最后一个组件
basename=$(basename "$path")
echo "$dirname/detached/$basename"
}
脚本功能
getDetachPath: 传入一个url,在最后一层前方加入一层/detached目录,例如:
输入 /data/clickhouse/data/test_db/table1/20240903ASSADAD
输出 /data/clickhouse/data/test_db/table1/detached/20240903ASSADAD
参数1: 输入地址
movefile: 将remote_host远程服务器的数据文件复制到当前服务器
参数1:数据文件前缀:如20240903代表partition为‘2024-09-03’, 202409代表所有2024年9月份的partition
参数2:数据库名称
2. Clickhouse存入detached数据
存储开始时间2023-09-01到结束时间2024-11-07的detached数据
#!/bin/bash
# 设置起始日期
start_date="2023-09-01"
# 设置结束日期
end_date="2024-11-07"
# 将起始日期转换为秒(从1970-01-01 00:00:00 UTC至今的秒数)
start_seconds=$(date -d "$start_date" +%s)
# 将结束日期转换为秒
end_seconds=$(date -d "$end_date" +%s)
# 循环遍历每一天
current_seconds=$start_seconds
while [ $current_seconds -le $end_seconds ]; do
# 将秒数转换回日期格式
current_date=$(date -d "@$current_seconds" +"%Y-%m-%d")
clickhouse-client --query="alter table test_db.table1 attach partition '$current_date'"
# 增加一天(86400秒=24小时)
current_seconds=$((current_seconds + 86400))
done