Hive:将两个地图合并为一列
Hive : Merge two maps into one column
我有一个蜂巢 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"}
我的目标 table 看起来像这样
create table myTarget(
my_col map<string, string>
)
现在我想将 mySource 中的两列组合成一个地图并将其提供给我的目标 table。基本上我想写一些像
insert into myTarget
select
some_method(col_1, col_2) as my_col
from mySource;
hive 中是否有可以执行此操作的内置方法?我用 collect_set 尝试了一些东西,但出现了很多错误
仅使用内置方法的解决方案。分解两个映射,UNION ALL 结果,收集 key:value
的数组,将数组与 ','
连接,使用 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 库会容易得多:
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;
我有一个蜂巢 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"}
我的目标 table 看起来像这样
create table myTarget(
my_col map<string, string>
)
现在我想将 mySource 中的两列组合成一个地图并将其提供给我的目标 table。基本上我想写一些像
insert into myTarget
select
some_method(col_1, col_2) as my_col
from mySource;
hive 中是否有可以执行此操作的内置方法?我用 collect_set 尝试了一些东西,但出现了很多错误
仅使用内置方法的解决方案。分解两个映射,UNION ALL 结果,收集 key:value
的数组,将数组与 ','
连接,使用 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 库会容易得多:
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;