首页 > 解决方案 > Hive:有条件地截断并加载表

问题描述

我正在尝试解决如果目标中所有类别的源表都可用的问题,则截断并加载目标表,否则不执行任何操作。

我还没有找到任何仅使用 hive 并最终使用Shell 脚本来解决此问题的解决方案。

是否可以避免shell脚本?

当前方法:

create_ind_table.hql

create temporary table temp.master_source_join
as select case when source.program_type_cd=master.program_type_cd then 1 else 0 end as IND
from source left join master
    on source.program_type_cd=master.program_type_cd;

--if all the categoies from source persent in master then will contain 1 else 0'
drop table if exists temp.indicator;
create table temp.indicator
as select min(ind)*max(ind) as ind from master_source_join;

如果所有源表类别都存在于主表中,以下是我调用的脚本来截断并加载主表。

tuncate_load_master.sh

beeline_cmd="beeline -u 'jdbc:hive2://abc.com:2181,abc1.com:2181,abc2.com:2181/;serviceDiscoveryMode=zooKeeper;zooKeeperNamespace=hiveserver2' --showHeader=flase --silent=true"
${beeline_cmd} -f create_ind_table.hql
## if indicator is 1 all the source category is present in master else not.

a=`${beeline_cmd} -e "select ind from temp.indicator;"`
temp=`echo $a | sed -e 's/-//g' | sed -e 's/+//g' | sed -e 's/|//g'`
echo $temp
if [ ${temp} -eq 1 ]
then
    echo "truncate and load the traget table"
    ${beeline_cmd} -e "insert overwrite table temp.master select * from temp.source;"
else
    echo "nothing to load"
fi

标签: hadoophivehiveql

解决方案


使用动态分区的查询将仅覆盖源数据集中存在的分区。将虚拟分区添加到您的表中,例如以下答案:https ://stackoverflow.com/a/47505850/2700344

您可以在同一个子查询中使用分析计算您的标志min()并按它过滤。

对于返回的所有行,计算的 IND 将相同。并且看起来解析 min() 就足够了,不需要计算 max()。按 IND=1 过滤。如果min() over()=0,它将不返回任何行并且不会覆盖表。

--enable dynamic partitioning
set hive.exec.dynamic.partition=true;
set hive.exec.dynamic.partition.mode=nonstrict;

insert overwrite table temp.master PARTITION(dummy_part) 
select s.col1, s.col2, --list all columns here you need to insert 
        'dummy_value' as dummy_part --dummy partition column 
from 
(
select s.*, 
      min(case when s.program_type_cd=m.program_type_cd then 1 else 0 end ) over() as IND
from source s left join master m
    on s.program_type_cd=m.program_type_cd
)s where ind=1 --filter will not return rows if min=0

推荐阅读