hive:将两个Map合并到一列中

hjzp0vay  于 2021-06-25  发布在  Hive
关注(0)|答案(1)|浏览(1599)

我有一张 hive table

create table mySource(
    col_1   map<string, string>,
    col_2   map<string, string>
)

下面是一张唱片的样子

col_1                col_2
{"a":1, "b":"2"}     {"c":3, "d":"4"}

我的目标表是这样的

create table myTarget(
        my_col   map<string, string>
    )

现在我想将mysource中的两列合并到一个Map中,并将其提供给我的目标表。基本上我想写一些

insert into myTarget
    select
        some_method(col_1, col_2) as my_col
    from mySource;

是否有一个内置的方法可以做到这一点?我用collect\u set做了一些尝试,但出现了很多错误

hivapdat

hivapdat1#

只使用内置方法的解决方案。分解两个贴图,合并所有结果,收集 key:value ,将数组与 ',' ,使用将字符串转换为Map str_to_map :

with mytable as (--Use your table instead of this
select 
map('a','1', 'b','2') as col_1, map('c','3', 'd','4') as col_2
)

select str_to_map(concat_ws(',',collect_set(concat(key,':',val)))) as mymap
from
(
select m1.key, m1.val 
  from mytable
       lateral view explode(col_1) m1 as key, val
union all
select m2.key, m2.val 
  from mytable
       lateral view explode(col_2) m2 as key, val
)s       
;

结果:

mymap

{"a":"1","b":"2","c":"3","d":"4"}

使用brickhouse library会更容易:

ADD JAR /path/to/jar/brickhouse-0.7.1.jar;
CREATE TEMPORARY FUNCTION COMBINE AS 'brickhouse.udf.collect.CombineUDF';

select combine(col_1, col_2) as mymap from mytable;

相关问题