場景
訂單數據之類的業務表,因爲有狀態要更新,比如訂單狀態,物流狀態之類的,需要同步很久之前的數據到Hive. 如何同步時在Hive中進行操作一次更新多個分區內的數據?
Hive 操作
- 設置Hive動態分區
SET hive.exec.dynamic.partition=true;
SET hive.exec.dynamic.partition.mode=nonstrict;
- 創建分區表:
源表:
CREATE TABLE `ods_binlog_person`(
`binlog_id` bigint,
`binglog_es` bigint,
`binlog_ts` bigint,
`binlog_type` string,
`id` bigint,
`name` string,
`score` int,
`created_at` string,
`updated` string)
PARTITIONED BY (`dt` string)
ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t';
加載數據:
load data inpath '/camus/exec/binlog/person/pt_hour=2022072400' into table ods_binlog_person partition (dt='2022072400')
目標表
CREATE TABLE IF NOT EXISTS temp_partition_table(
id string comment "字段id",
name string comment "字段註釋",
`score` int,
`created_at` string,
`updated` string
) COMMENT "分區表"
PARTITIONED BY(`dt` string)
STORED AS ORC
TBLPROPERTIES("orc.compress"="SNAPPY");
- 插入分區數據
insert overwrite table temp_partition_table partition(dt)
select
id,
name,
score,
created_at,
updated,
from_unixtime(unix_timestamp(created_at,'yyyy-MM-dd HH:mm:ss'), 'yyyyMMdd')
from ods_binlog_person where dt = 2022072400;
- 查看分區
show partitions temp_partition_table;
OK
dt=20220717
dt=20220720
Time taken: 0.175 seconds, Fetched: 2 row(s)
- 查看錶信息
show create table temp_partition_table;
或者
desc temp_partition_table
- 加載到目標表後, 可以刪除源表中的分區數據,避免數據冗餘
alter table ods_binlog_person drop partition(dt=2022072400)
結論
通過Hive動態分區, 我們就實現基於源表的業務時間生成目標表的分區, 並且將數據加載到對應分區中. 然後刪除源表對應分區的數據,避免數據冗餘節省空間.