zoukankan      html  css  js  c++  java
  • hive 存储,解析,处理json数据

     hive 处理json数据总体来说有两个方向的路走

    1、将json以字符串的方式整个入Hive表,然后通过使用UDF函数解析已经导入到hive中的数据,比如使用LATERAL VIEW json_tuple的方法,获取所需要的列名。

    2、在导入之前将json拆成各个字段,导入Hive表的数据是已经解析过得。这将需要使用第三方的SerDe。

    测试数据为新浪微博测试公开数据

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

    {"id": 1701439105,"ids": [2154137571,3889177061,1496915057,……,1663973284],"total_number": 493}

    第一种:

    导入数据

    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;

    解析数据:

    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不能跨越多行。

    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;
  • 相关阅读:
    Python3 sorted() 函数
    [Python网络编程]一个简单的TCP时间服务器
    [爬虫]统计豆瓣读书中每个标签下的前两百本书
    [leetcode]39. Combination Sum
    [leetcode]18. 4Sum
    [leetcode DP]72. Edit Distance
    [leetcode DP]120. Triangle
    [leetcode DP]91. Decode Ways
    [leetcode DP]70. Climbing Stairs
    [leetcode DP]64. Minimum Path Sum
  • 原文地址:https://www.cnblogs.com/qiaoyihang/p/8729368.html
Copyright © 2011-2022 走看看