【问题标题】:hive json data parsinghive json数据解析
【发布时间】:2017-07-12 20:37:30
【问题描述】:

我的 JSON 数据在表 json_table 和列中是这样的:json_col

{
    "href": "example.com",
    "Hosts": {
        "cluster_name": "test",
        "host_name": "test.iabc.com"
    },
    "metrics": {
        "cpu": {
            "cpu_user": [
                [
                    0.7,
                    1499795941
                ],
                [
                    0.3,
                    1499795951
                ]
            ]
        }
    }
}

我想把它放到一个表格 json_data 中,格式如下

+-------------+-------+------------+
| metric_type | value | timestamp  |
+-------------+-------+------------+
| cpu_user    | 0.7   | 1499795941 |
+-------------+-------+------------+
| cpu_user    | 0.3   | 1499795951 |
+-------------+-------+------------+

我尝试使用 get_json_object 获取值

select get_json_object(json_col,'$.metrics.cpu.cpu_user[1]') from json_table

,这给了我

[0.3,1499795951]

如何使用这里的explode 函数来获得所需的输出?

【问题讨论】:

    标签: json hadoop hive


    【解决方案1】:
    select  'cpu_user'      as metric_type 
           ,val_ts[0]       as val
           ,val_ts[1]       as ts
    
    from   (select  split(m.col,',') as val_ts
    
            from    json_table j
                    lateral view explode(split(regexp_replace(get_json_object(json_col,'$.metrics.cpu.cpu_user[*]'),'^\\[\\[|\\]\\]$',''),'\\],\\[')) m
            ) m
    ;
    

    +-------------+-----+------------+
    | metric_type | val |     ts     |
    +-------------+-----+------------+
    | cpu_user    | 0.7 | 1499795941 |
    | cpu_user    | 0.3 | 1499795951 |
    +-------------+-----+------------+
    

    【讨论】:

    • 像魅力一样工作
    【解决方案2】:

    您也可以基于 JSON 数据实现 SerDe 和 InputFormat 接口,而不是使用 UDF。

    这里有一些参考:

    http://blog.cloudera.com/blog/2012/12/how-to-use-a-serde-in-apache-hive/ https://github.com/xjtuzxh/inceptor-inputformat

    【讨论】:

    • 那么您是说 Hive UDF 还是内部函数无法解析 JSON?
    • 我只是给你另一种方法,我没有说UDF不能解析JSON
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-06
    • 2017-08-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多