hive的lateral view explode 功能

最近遇到一个神奇的hive功能:lateral view explode,感觉与Mysql中的group concat相反,将原本在一起的数据拆分成多行形成虚拟表,再与原表进行笛卡尔积。

一般模式:select column_A,column_B,tmp_table.tmp_column from db_name.test_tb lateral view explode(column_C) tmp_table as tmp_column;

 column_A,column_B,column_C 都是原表 db_name.test_tb的列(字段);

tmp_table:explode形成的新虚拟表,可以不写;

tmp_column:explode形成的列(字段);

注意:explode用于处理的是:array或者map类型的数据,而不是string类型的;但是可以通过split等函数把string转换成explode可以处理的格式。

1. 建表:

create table if not exists db_name.test_tb(id string,content string,comment string) row format delimited fields terminated by '\1' stored as textfile

2. 插入几行数据:

insert into db_name.test_tb values('1','Tom,Bob,Andy','测试1,测试2,测试3')
insert into db_name.test_tb values('2','Jack,Vicent,Wendy','测试11,测试22,测试33')

3. explode:加或者不加as

select explode(split(content,',')) tmp_content from db_name.test_tb

select explode(split(content,',')) as tmp_content from db_name.test_tb

4. lateral view + explode:建立笛卡尔积

select id,ex_con,comment from db_name.test_tb lateral view explode(split(content,',')) tmp_content as ex_con

5. 通过表名.列名形式

select id,tmp_content.ex_con,comment from db_name.test_tb lateral view explode(split(content,',')) tmp_content as ex_con

6. 不添加虚拟表的表名

select id,content,ex_con,comment from db_name.test_tb lateral view explode(split(content,',')) as ex_con

7. 多列进行 lateral view

select id,content,ex_con,comment,ex_com from db_name.test_tb lateral view explode(split(content,',')) tmp_content as ex_con lateral view explode(split(comment,',')) tmp_comment as ex_com;

由笛卡尔积:每个id将会出现9种情况,按顺序排列如上。

相当于在第6步上,再次对comment列进行lateral view explode,使得原来每个id的结果扩充了3倍(因为comment有3种值)。

#

https://zhuanlan.zhihu.com/p/115913870

https://blog.csdn.net/guodong2k/article/details/79459282

posted on 2020-08-30 00:17  落日峡谷  阅读(9568)  评论(0编辑  收藏  举报

导航