如何使用配置单元将 `string` 字段转换为 `map<int, int>` 字段?

How do I convert a `string` field to a `map<int, int>` field using 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 可以完成此操作?

遗憾的是,仅使用 Hive 本机函数无法将字符串或 map 转换为 map。您可以使用 brickhouse 收集功能。例如,如果您有 table mytablestr:

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 函数,请参阅 brickhouse site:

上的说明
json_map(concat('{', str, '}'), 'int,int')