首页 > 解决方案 > 将 hive 数组列转换为 map 列

问题描述

我有一个带有两个数组列的配置单元表,如下所示:

 col1        col2
a,b,c        1,2,3

我想将这两列转换为地图列,如下所示:

    col
  {a->1,b->2,c->3}

怎么做?

标签: arrayshadoophive

解决方案


分解数组,使用分隔符连接地图元素':',将元素收集到数组中,将数组连接成逗号分隔的字符串,使用str_to_map函数获取地图:

create table test_map as 
select 
array('a','b','c') col1, array(1,2,3) as col2
;

select str_to_map(concat_ws(',',collect_set(concat(c1.col,':',col2[c1.i] )))) as map_col
 from test_map t 
      lateral view posexplode(col1) c1 as i,col

结果:

map_col 
{"a":"1","b":"2","c":"3"}   

如果数组元素的数量有限,那么你可以不用爆炸:

select str_to_map(concat(col1[0],':',col2[0],',',
                         col1[1],':',col2[1],',',
                         col1[2],':',col2[2])
                 ) as map_col
 from test_map t 

推荐阅读