发布端到端解决方案。将 JSON 转换为 hive 表的分步过程:
第 1 步)安装 maven(如果还没有)
>$ sudo apt-get install maven
第 2 步)如果还没有安装 git
>sudo git clone https://github.com/rcongiu/Hive-JSON-Serde.git
步骤 3) 进入 $HOME/HIVE-JSON_Serde 文件夹
步骤 4) 构建 serde 包
>sudo mvn -Pcdh5 clean package
步骤 5) serde 文件将在
$HOME/Hive-JSON-Serde/json-serde/target/json-serde-1.3.7-SNAPSHOT-jar-with-dependencies.jar
步骤 6) 在 hive 中添加 serde 作为依赖 jar
hive> ADD JAR $HOME/Hive-JSON-Serde/json-serde/target/json-serde-1.3.7- SNAPSHOT-jar-with-dependencies.jar;
步骤 7)在 $HOME/books.json 中创建 json 文件(示例)
{"value": [{"id": "1","bookname": "A","properties": {"subscription": "1year","unit": "3"}},{"id": "2","bookname":"B","properties":{"subscription": "2years","unit": "5"}}]}
步骤 8) 在 hive 中创建 tmp1 表
hive>CREATE TABLE tmp1 (
value ARRAY<struct<id:string,bookname:string,properties:struct<subscription:string,unit:string>>>
)
ROW FORMAT SERDE 'org.openx.data.jsonserde.JsonSerDe'
WITH SERDEPROPERTIES (
'mapping.value' = 'value'
)
STORED AS TEXTFILE;
步骤 9) 将数据从 json 加载到 tmp1 表中
>LOAD DATA LOCAL INPATH '$HOME/books.json' INTO TABLE tmp1;
步骤10)创建一个tmp2表做爆炸操作表格tmp1,这个中间步骤是将多级json结构分解成多行
注意:如果您的 JSON 结构简单且单层,请避免此步骤
hive>create table tmp2 as
SELECT *
FROM tmp1
LATERAL VIEW explode(value) itemTable AS items;
步骤 11) 创建 hive 表并从 tmp2 表中加载值
hive>create table books as
select value[0].id as id, value[0].bookname as name, value[0].properties.subscription as subscription, value[0].properties.unit as unit from tmp2;
第 12 步)删除 tmp 表
hive>drop table tmp1;
hive>drop table tmp2;
步骤 13) 测试 hive 表
hive>select * from books;
输出:
id名称订阅单位
1 B 1 年 3
2 B 2 年 5