1、环境 apache-hive-3.1.3
2、原始数据
select name
from test0422
where name like '%-%';
3、拆分
select name, new_name
from
(
select name
from test0422
where name like '%-%'
) t
lateral view explode(split(name, '-')) a as new_name;
4、explode 函数
explode 函数用于打散行,将一行的数据拆分成一列。
语法格式:explode(arr/map) 。
explode 函数只接受 array 和 map 类型。如果要拆分 string 字符串类型,需要借助 split 函数把字段分割成一个数组。
① 拆分成多行
select explode(`array`(1,3,5,7,9)) as new_col;
拆分成多行
select explode(split('aaaaa-zzzz-ggggggggggg', '-')) as new_col;
② 拆分成多列
-- 拆分 map 类型(map 是 key-value 结构)
select explode(map_col) as (may_key_col, may_value_col) from table_1; -- 拆分成两列多行
5、lateral view
explode 函数不能关联原有的表中的其他字段,无法将结果插回原表。
-- 错误示例
select other_col, explode(array_col) as new_col
from table_1;
explode 函数不能与 group by、cluster by、distribute by、sort by 联用。
select 后面只能获得一个 explode 函数产生的视图,如果还要获取其他列,则需要使用 lateral view 将多个视图合并。
lateral view 用于和 UDTF 函数(explode、split)结合使用,主要解决在 select 使用 UDTF 做查询过程中,查询只能包含单个 UDTF,不能包含其他字段、以及多个 UDTF 的问题。
首先通过 UDTF 函数拆分成多行,再将多行结果组合成一个支持别名的虚拟表,虚拟表相当于再和主表关联, 从而达到添加 UDTF 生成的字段以外字段的目的, 即主表里的字段或者主表运算后的字段。
语法格式: lateral view UDTF(expression) table_view as new_column;