explode 和 lateral view
为什么把这两个放一块呢,因为这两个经常放在一起用啊。
explode与lateral view在关系型数据库中本身是不该出现的,因为他的出现本身就是在操作不满足第一范式的数据(每个属性都不可再分),本身已经违背了数据库的设计原理(不论是业务系统还是数据仓库系统),不过大数据技术普及后,很多类似pv,uv的数据,在业务系统中是存贮在非关系型数据库中,用json存储的概率比较大,直接导入hive为基础的数仓系统中,就需要经过ETL过程解析这类数据,explode与lateral view在这种场景下大显身手。
explode用法
在介绍如何处理之前,我们先来了解下Hive内置的 explode 函数,官方的解释是:explode() takes in an array (or a map) as an input and outputs the elements of the array (map) as separate rows. UDTFs can be used in the SELECT expression list and as a part of LATERAL VIEW. 意思就是 explode() 接收一个 array 或 map 类型的数据作为输入,然后将 array 或 map 里面的元素按照每行的形式输出。其可以配合 LATERAL VIEW 一起使用。光看文字描述很不直观,咱们来看看几个例子吧。
hive (default)> select explode(array(‘A’,‘B’,‘C’));
OK
A
B
C
Time taken: 4.188 seconds, Fetched: 3 row(s)
hive (default)> select explode(map(‘a’, 1, ‘b’, 2, ‘c’, 3));
OK
key value
a 1
b 2
c 3
SQL
explode函数接收一个数组或者map类型的数据,通常需要用split函数生成数组。
explode 配合解析Json 数组
这里有数据:
{“info”:[
{“AppName”:“SogouExplorer_embedupdate”,“pepper”:"-1"},
{“AppName”:“SogouExplorer_embedupdate”,“pepper”:"-1"},
{“AppName”:“SogouExplorer_embedupdate”,“pepper”:"-1"},
{“AppName”:“2345Explorer_embedupdate”,“plugin”:"-1"},
{“AppName”:“SogouExplorer_embedupdate”,“pepper”:"-1"}
]}
现在需要将AppName和pepper提取出来,然后按行存放,一行一个,首先我们按照上一节我们学习的Json 处理的函数进行尝试