Hive JsonSerde

数据直接写入HDFS,通过Hive External关联数据源是一种常见的数据写入方案。本文介绍通过Hive External表关联HDFS json数据源的方案和一些常见问题。

Serde

Hive Serde 是一个HiveDeserializer and HiveSerializer接口的集合, 负责将输入的数据序列化成规定的数据格式,或则将输入的数据反序列化成规定的格式。JsonSerde就是实现了Serde接口

《Hive JsonSerde》 image.png

hive执行sql查询,加载数据的时候会通过Serde将本地数据序列化成HCatRecord返回给Hive.

《Hive JsonSerde》 image.png

JsonSerde的deserialize的函数实现通过JsonParser类,解析json数据,填充DefaultHCatRecord.

使用Hive自带的Jsonserde

修改hive-site.xml,增减jsonserde jar包

<property>
   <name>hive.aux.jars.path</name>
   <value>[file:///Users/titengjiang/Documents/DeveloperTool/hive/apache-hive-1.2.2-bin/lib/hive-hcatalog-core-1.2.2.jar</value>](http://file:///Users/titengjiang/Documents/DeveloperTool/hive/apache-hive-1.2.2-bin/lib/hive-hcatalog-core-1.2.2.jar</value>)
</property>

创建表

CREATE EXTERNAL TABLE if not exists hiveJsonserdeDemo (
    col1 string,
    col2 string,
    col3 string,
    col4 string,
    col5 string,
    col6 bigint,
    col7 bigint,
    col8 bigint,
    col9 bigint,
    col10 bigint
)
ROW FORMAT SERDE 'org.apache.hive.hcatalog.data.JsonSerDe'
LOCATION 'hdfs://localhost:9000/demo/hive-jsonserde-demo/';

如果没有添加hive.aux.jars.path路径会出现如下错误

Cannot validate serde: org.apache.hive.hcatalog.data.jsonSerde

《Hive JsonSerde》 image.png

写入正常测试数据,每个json通过\n分割

《Hive JsonSerde》 image.png

通过hive beeline查询刚才写入的数据

《Hive JsonSerde》 image.png

发现数据正常写入

hive jsonserde常见的问题

hive查询时候遇到错误JSON格式数据整个任务会终止

意思说如果插入数据中有某个json发生损坏整个查询会发生异常导致中断,下面例子我们模拟写入一个错误格式的json数据看下会出现什么问题。

《Hive JsonSerde》 image.png

写入完成后再次查询出现如下异常

Error: java.io.IOException: org.apache.hadoop.hive.serde2.SerDeException: org.codehaus.jackson.JsonParseException: Unexpected character

《Hive JsonSerde》 image.png

解决办法是通过替换Jsonserde实现来完成,因为数据写入中难免会出现异常数据。会再之后详细介绍。

写入的每条JSON必须分割,否者无法解析

《Hive JsonSerde》 image.png

通过模拟写入不分割JSON数据测试

《Hive JsonSerde》 image.png

发现写入的数据都已经损坏无法独读出###使用Hive自带的Jsonserde

使用Hive自带的org.openx.data.jsonserde.JsonSerDe替换重新测试

下载org.openx.data.jsonserde.JsonSerDe jar 按照上面办法添加到Aux path中

CREATE EXTERNAL TABLE if not exists hiveJsonserdeDemo (
    col1 string,
    col2 string,
    col3 string,
    col4 string,
    col5 string,
    col6 bigint,
    col7 bigint,
    col8 bigint,
    col9 bigint,
    col10 bigint
)
ROW FORMAT SERDE 'org.apache.hive.hcatalog.data.JsonSerDe'
LOCATION 'hdfs://localhost:9000/demo/hive-jsonserde-demo/';

测试写入错误格式json数据

《Hive JsonSerde》 image.png

发现错误数据不会影响sql正常运行

相关资源

org.openx.data.jsonserde.JsonSerDe下载地址:https://github.com/rcongiu/Hive-JSON-Serde

测试demo下载地址:https://github.com/ttting/hive-jsonserde-demo

    原文作者:TTTing听
    原文地址: https://www.jianshu.com/p/043223b0024d
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞