如何从配置单元Map中仅获取键列表

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

我在配置单元的一列中存储了一个Map,每行的键可以不同。我怎样才能从每个Map上得到一个只有钥匙的列表?

eyh26e7m

eyh26e7m1#

函数Map键(map)返回一个无序数组,其中包含输入Map的键。
示例,请参见代码中的注解:

with mydata as (
    select 1 id, map('key11','val11','key12','val12','key13','val13') as mymap
    union all
    select 2 id, map('key21','val21','key22','val22','key13','val13') as mymap --Key13 also exist in first row
    )

select id, map_keys(d.mymap) keys
  from mydata d
;

结果:

id  keys
1   ["key11","key12","key13"]
2   ["key21","key22","key13"]

如果需要所有行中唯一键的列表,请分解数组并使用collect\u set再次收集,它将返回不同键的数组:

with mydata as (
select 1 id, map('key11','val11','key12','val12','key13','val13') as mymap
union all
select 2 id, map('key21','val21','key22','val22','key13','val13') as mymap --Key13 also exist in first row
)

select --id, 
       collect_set(key) as keys
  from mydata d
       lateral view outer explode(map_keys(d.mymap)) e as key
 --group by id   --without id in groupby you get the distinct list of keys in all rows
                 --with id in groupby you get list of map keys for each row
;

结果:

["key11","key12","key13","key21","key22"]

相关问题