【问题标题】:Get particular values from a string in hive从 hive 中的字符串中获取特定值
【发布时间】:2019-05-22 22:55:51
【问题描述】:

我有一个蜂巢表,两列都是字符串

name            details
"john" , {"addr":"NY","phone":"1234"}
"john" , {"addr":"CA", "phone":"7145"}
"mary" , {"addr":"BOS","phone":"1234"}  

有没有办法将字符串列转换为 JSON 排序以通过键访问值。 例如,如果我运行查询

SELECT name, details['addr'] , details['phone'] FROM table_a;

我应该得到 约翰,纽约,1234 加利福尼亚州约翰,7145 玛丽,BOS,1234

【问题讨论】:

    标签: json hive hiveql


    【解决方案1】:

    您可以使用get_json_object,然后从字符串中访问addrphone

    hive>  with cte as (
            select string('"john"')col1,
                   string('{"addr":"NY","phone":"1234"}')col2)
            select regexp_replace(col1,"\"","")col1,get_json_object(col2,'$.addr')col2 
            from cte;
    

    Result:

    col1    col2
    john    NY
    

    要转义引号,我们还可以使用带有引号字符的 csv serde,如 here 所述。

    【讨论】:

      【解决方案2】:

      另一种使用str_to_map的方法:

      select name, details_map['addr'] as addr , details_map['phone'] as phone
      from 
      (
      select name, str_to_map(regexp_replace(details,'\\{|\\}| ?\\"','')) as details_map
      from your_table
      )s;
      

      【讨论】:

        猜你喜欢
        • 2013-11-20
        • 1970-01-01
        • 1970-01-01
        • 2014-01-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多