Hive的函数高阶应用
explode函数
explode属于UDTF函数,表生成函数,输入一行数据输出多行数据。
功能:
explode() takes in an array (or a map) as an input and outputs the elements of the array (map) as separate rows. --explode接收map array类型的参数 把map或者array的元素输出,一行一个元素。 explode(array(11,22,33)) 11 22 33 select explode(`array`(11,22,33,44,55)); select explode(`map`("id",10086,"name","allen","age",18));
lateral view 侧视图
侧视图的原理是将UDTF的结果构建成一个类似于视图的表,然后将原表中的每一行和UDTF函数输出的每一行进行连接,生成一张新的虚拟表
背景
UDTF函数生成的结果可以当成一张虚拟的表,但是无法和原始表进行组合查询
select name,explode(location) from test_message; --这个sql就是错误的 相当于执行组合查询
从理论层面推导,对两份数据进行join就可以了
但是,hive专门推出了lateral view侧视图的语,满足上述需要。
功能:把UDTF函数生成的结果和原始表进行关联,便于用户在select时间组合查询、 lateral view是UDTf的好基友好搭档,实际中经常配合使用。
语法:
--lateral view侧视图基本语法如下 select …… from tabelA lateral view UDTF(xxx) 别名 as col1,col2,col3……; --针对上述NBA冠军球队年份排名案例,使用explode函数+lateral view侧视图,可以完美解决 select a.team_name ,b.year from the_nba_championship a lateral view explode(champion_year) b as year; --根据年份倒序排序 select a.team_name ,b.year from the_nba_championship a lateral view explode(champion_year) b as year order by b.year desc; --统计每个球队获取总冠军的次数 并且根据倒序排序 select a.team_name ,count(*) as nums from the_nba_championship a lateral view explode(champion_year) b as year group by a.team_name order by nums desc;
行列转换
多行转单列
collect_set --把多行数据收集为一行 返回set集合 去重无序
collect_list --把多行数据收集为一行 返回list集合 不去重有序
字符串拼接函数
concat --直接拼接字符串
concat_ws --指定分隔符拼接
select concat("it","cast","And","heima");
select concat("it","cast","And",null);
select concat_ws("-","itcast","And","heima");
select concat_ws("-","itcast","And",null);
单列转多行
技术原理: explode+lateral view
--原表 +-------+-------+--------+--+ | col1 | col2 | col3 | +-------+-------+--------+--+ | a | b | 1,2,3 | | c | d | 4,5,6 | +-------+-------+--------+--+ --目标表 +------