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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM