` 使用 hive 的字段?,dictionary,types,hive,casting,hiveql"/>

首页 > 解决方案 > 如何将“字符串”字段转换为“地图”` 使用 hive 的字段?

问题描述

我有一个字段是地图的字符串表示形式,例如其中一行是"1:2,3:4". 使用str_to_map我设法将该字段转换为的函数map<string, string>,该示例将表示为{"1":"2", "3":"4"}。不幸的是,我需要这个字段map<int, int>(或者实际上是任何整数类型),示例再次表示为{1:2, 3:4}. 有什么方法可以在不使用 UDF 的情况下在 Hive 中完成此操作?如果没有,是否有一个简单的 UDF 可以做到这一点?

标签: dictionarytypeshivecastinghiveql

解决方案


不幸的是,仅使用 Hive 本机函数无法将 string 或 map<string, string> 转换为 map<int, int>。您可以使用砖房收集功能。例如,如果您有mytable带有列的表str

add jar '~/brickhouse/target/brickhouse-0.6.0.jar'; --check brickhouse site https://github.com/klout/brickhouse for instructions

create temporary function collect as 'brickhouse.udf.collect.CollectUDAF';
 
select d.str, collect(int(key), int(value)) as result
  from mytable d
       lateral view outer explode(str_to_map(str)) e as key, value
group by d.str;

他们还有另一个非常有用的函数 json_map,它可以用来将 JSON 字符串转换为所需类型的映射,甚至更简单,而不会爆炸初始映射。您可以通过连接 { 和 } 将您的字符串转换为 JSON,然后应用 json_map 函数,请参阅砖屋网站上的说明:

json_map(concat('{', str, '}'), 'int,int')

推荐阅读