hive 作为一个常用的分布式数据库,往往会存储多种数据源,其中xml格式的数据导入到hive中有多种方式,借助etl工具,如datax,kettle, nifi等都可以轻松实现,在这里我来给大家介绍一种hive直接读取xml格式数据,并将其转换为行的方式
xml数据文件test.xml:
<?xml version="1.0" standalone="no" ?><Root><student><name>lisi</name><age>20</age><address>shanghai</address></student><student><name>wangwu</name><age>26</age><address>guangzhou</address></student><student><name>zhangsan</name><age>44</age><address>shenzhen</address></student><student><name>xiaoming</name><age>22</age><address>beijing</address></student><student><name>xiangmin</name><age>56</age><address>zhengzhou</address></student></Root>
创建hive表:
CREATE EXTERNAL TABLE readxml(xmlstr STRING) LOCATION '/tmp/xmlread';
将文件上传到hdfs中目录/tmp/xmlread下:
hadoop fs -put test.xml /tmp/xmlread
查询表中的数据:
select xmlstr from readxml;
结果如下:
注意:查询的结果要为一行,如果为多行,通过行转列等函数,转化为一个字符串
解析字符串中的数据,用到的函数有xpath,posexplode,lateral view等等,具体使用方法自行去百度,具体sql如下:
select id,name_val,age_val,address_val from (
SELECT
xpath(xmlstr,'Root/student/name/text()') name,
xpath(xmlstr,'Root/student/age/text()') age,
xpath(xmlstr,'Root/student/address/text()') address
FROM readxml) t --使用xpath解析出所有字段,返回list
lateral view posexplode(name) demo as id,name_val --爆炸list
lateral view posexplode(age) demo as id1,age_val
lateral view posexplode(address) demo as id2,address_val
where id1=id --posexplode返回的数据会做笛卡尔积,通过索引位置过滤
and id2=id;
返回的结果如下:
以上就是hive解析xml字符串的全过程,json的解析思路类似,有兴趣的朋友可以去研究下