Hive嵌套数组结构体字段如何提取各type值转为独立列
Hive嵌套复杂类型字段提取方案
假设你的表名为your_table,待处理的嵌套字段名为nested_col,需要保留的其他维度字段为id、dt等,可根据实际场景替换对应字段名。
场景1:外层数组固定只有1个元素(和示例数据结构一致)
该方案无需炸开外层数组,性能更高:
select id, dt, max(case when struct_item.type = 'PROFIT' then struct_item.value end) as PROFIT, max(case when struct_item.type = 'NET' then struct_item.value end) as NET, max(case when struct_item.type = 'TOTAL' then struct_item.value end) as TOTAL from your_table -- 直接取外层数组第0位元素后炸开内层数组 lateral view explode(nested_col[0]) t as struct_item group by id, dt;
场景2:外层数组可能存在多个元素
如果外层数组长度不固定,需要先炸开外层数组再处理:
select id, dt, max(case when struct_item.type = 'PROFIT' then struct_item.value end) as PROFIT, max(case when struct_item.type = 'NET' then struct_item.value end) as NET, max(case when struct_item.type = 'TOTAL' then struct_item.value end) as TOTAL from your_table -- 先炸开外层数组得到内层数组 lateral view explode(nested_col) t1 as inner_array -- 再炸开内层数组得到每个struct元素 lateral view explode(inner_array) t2 as struct_item group by id, dt;
补充说明
- 若需要数值类型计算,可将提取到的
value用cast()函数转换为对应数值类型 - 若同一条数据中存在多个同type的结构体,可将
max替换为sum/collect_list等符合业务需求的聚合函数
内容的提问来源于stack exchange,提问作者user1761325
相关产品推荐
相关产品推荐

