hive 對json資料的處理

2021-08-21 03:40:54 字數 2333 閱讀 1521

hive 處理json資料總體來說有兩個方向的路走

1、將json以字串的方式整個入hive表,然後通過使用udf函式解析已經匯入到hive中的資料,比如使用lateral view json_tuple的方法,獲取所需要的列名。

2、在匯入之前將json拆成各個字段,匯入hive表的資料是已經解析過得。這將需要使用第三方的serde。

該資料採用json格式儲存,

id代表當前使用者微博的id,

ids代表當前微博使用者關注其他微博使用者的id列表,

total_number是關注微博使用者的總量。

第一種:

匯入資料

create

table

ifnot

exists

tmp_json_test (

json string

) stored

astextfile ;

load data local inpath '

/opt/datas/weibotest.json

' overwrite into

table tmp_json_test;

解析資料:

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

第二種:

第二種方式相比第一種更靈活,更通用。重要的是每行必須是乙個完整的json,乙個json不能跨越多行。

如果要想在hive中使用jsonserde,需要把jar新增到hive類路徑中:

add jar json-serde-1.3.7-jar-with-dependencies.jar;

匯入資料

create

table

tmp_json_array (

id string,

ids array

,`total_number`

int)

row format serde

'org.openx.data.jsonserde.jsonserde

'stored

astextfile;

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

,`total_number`

int)

row format serde

'org.openx.data.jsonserde.jsonserde

'"ids")

stored

as textfile;

hive處理json資料

今天練習一下在hive中使用get json object這個函式,首先建立乙個表將json格式的資料匯入 create table json01 line string 將資料匯入 load data local inpath home hadoop json test into table js...

hive處理json資料

1.載入hcatalog包,這個包已經在hive目錄檔案中 hive add jar hcatalog share hcatalog hive hcatalog core 1.2.0.jar 2.建立處理json格式資料的表 注意 org.apache.hive.hcatalog.data.json...

Hive處理json格式資料

1 資料示例 假設info表中存有兩個字段,分別是id,content content 2 使用hive內建函式 get json object json tuple regexp replace 3 說明 使用get json object 解析content,獲取properties,使用reg...