Hive之lateral view和explode的使用详解

关于explode函数

explode()其实就是一个UDTF——用户自定义表生成函数,而表生成函数官方定义是接受零个或多个输入,产生多列或多行的输出,就像explode的含义一样,生成爆炸一样的效果,将数据散开。
explode()一般接受Array类型的数组为入参,对数据中的元素进行迭代,再返回多行结果,比如:
select explode(Array(1,2,3)) from  t
返回结果为:
在这里插入图片描述
为了更好的切合实际运用和大家理解,我使用一个生产中的字段格式,该格式是某网站的爬虫数据,如下
格式在这里插入图片描述

该列是一个json对象,其中有很多元素,其中feture元素是特征描述,以‘ ’为分割符,格式如下
在这里插入图片描述
我们想做的就是将这个feature字段中的每个特征解析为多行,但现在这个feture在json对象中,所以,我们先调用get_json_object解析json,如下:

select
  get_json_object(result_contxt, '$.feature') as feature
from
 testtable
where
  p_day = '20191208'

查询结果为:
在这里插入图片描述

但explode或者说UDTF函数有两个使用限制,第一,我们无法从包含UDTF的语句中正常查询出其他的列,如下

select
	explode(split(t.feature,' '))
    ,url
from
(select
  get_json_object(result_contxt, '$.feature') as feature
  ,url
from
testtable
where
  p_day = '20191208'
 ) 

执行sql异常Error while compiling statement: FAILED: SemanticException 1:55 Only a single expression in the SELECT clause is supported with UDTF’s. Error encountered near token 'url’

第二,UDTF无法内嵌在其他函数中,如下

select
	distinct(explode(split(t.feature,' ')))
from
(select
  get_json_object(result_contxt, '$.feature') as feature
  ,url
from
testtable
where
  p_day = '20191208'
 )

执行sql异常Error while compiling statement: FAILED: SemanticException [Error 10081]: UDTF’s are not supported outside the SELECT clause, nor nested in expressions

所以问题来了,如何能够在使用explode或是UDTF时,同时查询多列,这时就需要lateral view——侧视图来实现功能了

如下

select
	features_1,
    url
from
(select
  get_json_object(result_contxt, '$.feature') as feature
  ,url
from
	testtable
where
  p_day = '20191208'
 ) t
lateral view explode(split(feature,' ')) tempview as features_1

这里的 tempview是临时表名,它与上面的子查询结果是笛卡尔积关联的,查询结果如下
在这里插入图片描述
以上就是lateral view的用法,在实际开发中,lateral view 除了可以方便地将UDTF的行转列结果结合其他查询使用,还可以做两列合并等操作,当然也可以使用union all,具体需求决定具体使用,也跟个人习惯有一定关系~

发布了14 篇原创文章 · 获赞 1 · 访问量 684

猜你喜欢

转载自blog.csdn.net/qq_33891419/article/details/103297121
今日推荐