hive中的lateral view 与 explode函数的使用

hive中的lateral view 与 explode函数的使用

背景介绍:

explode与lateral view在关系型数据库中本身是不该出现的。

因为他的出现本身就是在操作不满足第一范式的数据(每个属性都不可再分)。本身已经违背了数据库的设计原理(不论是业务系统还是数据仓库系统),在面向分析的数据库 数据仓库中,发生了改变。

explode函数可以将一个array或者map展开,
其中explode(array)使得结果中将array列表里的每个元素生成一行;
explode(map)使得结果中将map里的每一对元素作为一行,key为一列,value为一列,
一般情况下,直接使用即可,也可以根据需要结合lateral view 使用
  • explode的使用
001,allen,usa|china|japan,1|3|7
002,kobe,usa|england|japan,2|3|5
 
create table test_message(id int,name string,location array<string>,city array<int>) row format delimited fields terminated by ","
collection items terminated by '|';
​
load data local inpath "/root/hivedata/test_message.txt" into table test_message;

查看array的元素 用下标进行寻找,类似于其他编程语言中的数组访问

select location[1] from test_message;

使用explode

select explode(location) from test_message;
​
select name,explode(location) from test_message; 报错
当使用UDTF函数的时候,hive只允许对拆分字段进行访问的。

lateral view(侧视图)

​ lateral view为侧视图,意义是为了配合UDTF来使用,把某一行数据拆分成多行数据.不加lateral view的UDTF只能提取单个字段拆分,并不能塞会原来数据表中.加上lateral view就可以将拆分的单个字段数据与原始表数据关联上.

在使用lateral view的时候需要指定视图别名和生成的新列别名

tabelA lateral view UDTF(xxx) 视图别名 as a,b,c
​
​
select subview.* from test_message lateral view explode(location) subview as lc;
subview为视图别名,lc为指定新列别名
​
select name,subview.* from test_message lateral view explode(location) subview as lc;
​
lateral view explode 相当于一个拆分location字段的虚表,然后与原表进行关联.
  • json_tuple()函数也是UDTF函数,因为一个json字符串对应了解析出n个字段.与原表数据关联的时候需要使用lateral view
select id from table lateral view json_tuple(property,'tag_id','tag_type’);
原文地址:https://www.cnblogs.com/alexzhang92/p/11073358.html