hive:explode() 与 lateral view

来源:互联网 发布:福建广播电视网络 编辑:程序博客网 时间:2024/05/29 12:30

一、解决如下问题

如何由上面的宽表变成下面的窄表?

这里写图片描述
这里写图片描述

二、explode()

explode() takes in an array (or a map) as an input and outputs the elements of the array (map) as separate rows.
explode() 函数接收array或map类型数据,并分行返回数据的每一个元素。注意输入必须是array或map类型,字符串不可以。因此好多情况下都要借助split()。
实例:
select explode(split(test_data,’,’)) from test
输出:
这里写图片描述

三、lateral view

上面实现了单列的行转列,但是并没有跟date字段进行匹配。这就需要用到lateral view。
Lateral view:lateral view is used in conjunction with user-defined table generating functions such as explode(). As mentioned in Built-in Table-Generating Functions, a UDTF generates zero or more output rows for each input row. A lateral view first applies the UDTF to each row of base table and then joins resulting output rows to the input rows to form a virtual table having the supplied table alias.
Lateral view:lateral view用于和split、explode等UDTF一起使用的,能将一行数据拆分成多行数据,在此基础上可以对拆分的数据进行聚合,lateral view首先为原始表的每行调用UDTF,UDTF会把一行拆分成一行或者多行,lateral view在把结果组合,产生一个支持别名表的虚拟表。
select date date_t,test_data_t from test lateral view explode(split(test_data,’,’)) test_data_t as test2;
输出:
这里写图片描述

四、这时就可以用聚合函数进行聚类统计了

可以按date_t对test_data_t进行sum、count、avg等等。

原创粉丝点击