Hive处理json数据

一、测试数据

该数据采用json格式存储:
id:代表当前用户微博的id;
ids:代表当前微博用户关注其他微博用户的id列表;
total_number:关注微博用户的总量。

{"id": 1701439105,"ids": [2154137571,3889177061,1496915057,1663973284],"total_number": 493}
{"id": 1701439106,"ids": [2154137572,3889177063,1496915058,1663973285],"total_number": 494}

二、数据存储及解析

方式一:
将源系统json数据以字符串的数据类型写入Hive表中,然后通过函数解析获取json数据。

数据建表及写入
hive (myhive)> create table myhive.tbs_json_test(
    json_data string
)
stored as textfile;
hive (myhive)> load data local inpath '/install/hivedatas/json_data.json' into table myhive.tbs_json_test;
数据解析
hive (myhive)> select get_json_object(json_data,'$.ids') from myhive.tbs_json_test;
hive (myhive)> select t2.* from myhive.tbs_json_test t1 lateral view json_tuple(t1.json_data,'id','ids') t2 as c1,c2;

get_json_object:用来解析json字符串的一个字段;
json_tuple:用来解析json字符串的多个字段。

方式二:
将源系统json数据按照key拆成多个Hive数据字段,加载对应的jar包后,导入json数据到Hive数据表对应字段中。

数据建表及写入
hive (myhive)> add jar /install/apache-hive-3.1.2/hcatalog/share/hcatalog/ hive-hcatalog-core-3.1.2.jar;

hive (myhive)>create table myhive.tbs_json_test2(
id string,
ids array,
total_number int)
row format serde 'org.apache.hive.hcatalog.data.JsonSerDe'
stored as textfile;
hive (myhive)> load data local inpath '/install/hivedatas/json_data.json' into table myhive.tbs_json_test2;

直接select 字段名称即可查看数据表。
注意:
1、如果json数据不符合规范查询则会报错。增加如下配置会挑过错误数据,错误数据将变为NULL.

alter table myhive.tbs_json_test2 set serdeproperties( "ignore.malformed.json" = "true");

2、如果json数据中包含Hive关键字,数据写入时有问题,可通过SerDe使用SerDe属性将Hive列映射到新名称的属性下。
例如:如果ids为Hive关键字,则将ids改为ids_alias创建Hive数据表。

hive (myhive)>create table myhive.tbs_json_test3(
id string,
ids_alias array,
total_number int)
row format serde 'org.apache.hive.hcatalog.data.JsonSerDe'
with serdeproperties("mapping.ids_alias"="ids")
stored as textfile;

你可能感兴趣的:(Hive处理json数据)