首页 > 解决方案 > 如何在 Hive 的复杂列中选择有限数量的值?

问题描述

我有一张桌子,上面有 id、name 和 proficiency。熟练度列是具有地图数据类型的复杂列。如何将复杂地图数据类型中显示的数据量限制为 2?

示例表

ID  | name   | Proficiency
003 | John   | {"Cooking":3, "Talking":6 , "Chopping":8, "Teaching":5}
005 | Lennon | {"Cooking":3, "Programming":6 }
007 | King   | {"Chopping":8, "Boxing":5 ,"shooting": 4}

我想在 select 语句之后显示什么

ID  | name   | Proficiency
003 | John   | {"Cooking":3, "Talking":6 }
005 | Lennon | {"Cooking":3, "Programming":6 }
007 | King   | {"Chopping":8, "Boxing":5 }

标签: dictionaryhivehiveql

解决方案


对于所需的固定数量的映射元素,这可以使用返回键和值数组的函数轻松完成map_keys()map_values()您可以使用数组索引访问键和值,然后使用map()函数再次组装映射:

with MyTable as -------use your table instead of this subquery
(select stack(3,
'003', 'John'  , map("Cooking",3,  "Talking",6 , "Chopping",8, "Teaching",5),
'005', 'Lennon', map("Cooking",3,  "Programming",6 ),
'007', 'King'  , map("Chopping",8, "Boxing",5 ,"shooting", 4)
) as (ID, name, Proficiency)
) -------use your table instead of this 

select t.ID, t.name, 
       map(map_keys(t.Proficiency)[0], map_values(t.Proficiency)[0],
           map_keys(t.Proficiency)[1], map_values(t.Proficiency)[1]
          ) as Proficiency
  from MyTable t

结果:

t.id    t.name  proficiency
003 John    {"Cooking":3,"Talking":6}
005 Lennon  {"Cooking":3,"Programming":6}
007 King    {"Boxing":5,"shooting":4}

map不保证按定义排序,map_keys、map_values按定义返回无序数组,但是在同一个子查询中使用时顺序一致,所以key是匹配到对应的值的。


推荐阅读