hive 處理json數據整體來講有兩個方向的路走json
一、將json以字符串的方式整個入Hive表,而後經過使用UDF函數解析已經導入到hive中的數據,好比使用LATERAL VIEW json_tuple的方法,獲取所須要的列名。app
二、在導入以前將json拆成各個字段,導入Hive表的數據是已經解析過得。這將須要使用第三方的SerDe。函數
測試數據爲新浪微博測試公開數據測試
該數據採用json格式存儲,
id表明當前用戶微博的id,
ids表明當前微博用戶關注其餘微博用戶的id列表,
total_number是關注微博用戶的總量。spa
{"id": 1701439105,"ids": [2154137571,3889177061,1496915057,……,1663973284],"total_number": 493}.net
第一種:code
導入數據orm
CREATE TABLE IF NOT EXISTS tmp_json_test ( json string ) STORED AS textfile ; load data local inpath '/opt/datas/weibotest.json' overwrite into table tmp_json_test;
解析數據:blog
select get_json_object(t.json,'$.id'), get_json_object(t.json,'$.total_number') from tmp_json_test t ; select t2.* from tmp_json_test t1 lateral view json_tuple(t1.json, 'id', 'total_number') t2 as c1, c2; 方法一使用函數get_json_object , 方法二使用函數 json_tuple
第二種:ci
第二種方式相比第一種更靈活,更通用。重要的是每行必須是一個完整的JSON,一個JSON不能跨越多行。
1. 下載Jar
使用以前先下載jar:
http://www.congiu.net/hive-json-serde/
若是要想在Hive中使用JsonSerde,須要把jar添加到hive類路徑中:
add jar json-serde-1.3.7-jar-with-dependencies.jar;
導入數據
CREATE TABLE tmp_json_array ( id string, ids array<string>, `total_number` int) ROW FORMAT SERDE 'org.openx.data.jsonserde.JsonSerDe' STORED AS TEXTFILE; LOAD DATA LOCAL INPATH '/opt/datas/weibotest.json' OVERWRITE INTO TABLE tmp_json_array;
倒入以後就能夠隨便使用了
select * from tmp_json_array where array_contains(ids,'2813165271') or array_contains(ids,'1419789200');
須要注意的是當你的數據中包含有不符合json規範的行時,運行查詢會報異常
測試能夠增長配置用以跳過錯誤數據
ALTER TABLE weibo_json SET SERDEPROPERTIES ( "ignore.malformed.json" = "true");
在運行查詢不會報錯,可是壞數據記錄將變爲NULL。
最後須要提醒的是當你的json數據中包含hive關鍵字時,導入的數據會有問題,此時 SerDe可使用SerDe屬性將hive列映射到名稱不一樣的屬性
若是ids是hive關鍵字的話,更改建表語句以下:
CREATE TABLE tmp_json_array ( id string, ids_alias array<string>, `total_number` int) ROW FORMAT SERDE 'org.openx.data.jsonserde.JsonSerDe' WITH SERDEPROPERTIES ("mapping.ids_alias"="ids") STORED AS TEXTFILE;