SQOOP增量抽取时,在HIVE中实现类似Oracle的merge操作

数据仓库建设中的数据抽取环节,常常需要增量抽取业务库数据。但业务库数据不是一层不变的,会根据时间发生状态变更,那么就需要同步更新变化数据到HIVE中。过去在Oracle上做数据仓库时,可以使用merge的方法合并新老数据。但hive中没有该功能,本文旨在通过sqoop抽取后,自动实现数据合并。

表设计

将抽取表分为三张,

  1. 一张_arc表,保存每日合并后的快照,根据pt字段分区
  2. 一张_inc表,用于保存当日抽取的增量数据,根据pt字段分区
  3. 一张不带后缀的表,指向最终表给后续ETL任务使用。

步骤

  1. 使用sqoop进行hive import,将数据导入_inc表
  2. 核心,使用full join、coalesce、if组合的SQL合并将inc表当日分区数据与arc更前一日分区数据合并到_arc表当日分区中。
  3. 最终表通过hive命令set location指向_arc当日分区。

代码要点:

merge SQL

use ods; 
insert overwrite table mytable_arc partition (pt='20200407') 
select coalesce(a.id,b.id), if(a.id is null, b.type, a.type), if(a.id is null, b.amt, a.amt) from (
  select id, type, amt
  from mytable_inc where pt='20200407'
) a full join (
  select id, type, amt
  from mytable_arc where pt='20200406'
) b on a.id = b.id
;

hive set location

use ods; 
alter table mytable set location 'hdfs://hadoop01:9000/user/hive/warehouse/ods.db/mytable_arc/pt=20200407'"