【问题标题】:Parsing string in a hive table在配置单元表中解析字符串
【发布时间】:2019-09-11 21:13:36
【问题描述】:

我有一个 hive 表,它有两列 (day, type_of_day) 都是字符串类型

"monday"    [{"temp" : 45, "weather": "rainny"}, {"temp" : 25, "weather": "sunny"}, {"temp" : 15, "weather": "storm"}]
"tuesday"   [{"temp" : 5, "weather": "winter"}, {"temp" : 10, "weather": "sun"}, {"temp" : 18, "weather": "dawn"}]

我想拆分(我想爆炸是技术术语)然后只获取每天的天气列表。我熟悉如何在 python 中执行此操作,但有没有办法在 hive 中直接执行此操作。

"monday"    [45, 25, 15]
"tuesday"   [5, 10, 18]

【问题讨论】:

  • 初始字符串也包含方括号,但不是数组,是字符串,对吧?我问这个是因为它像数组一样显示。你需要输出为数组吗?或字符串 "[45, 25, 15]" ?
  • 是的,它是一个字符串。我希望输出是一个数组。

标签: sql arrays hive hiveql explode


【解决方案1】:

使用您的数据示例进行测试。用您的表替换 CTE。阅读代码中的cmets:

with your_table as (--use your table instead of this CTE
select stack(2,
             "monday",'[{"temp" : 45, "weather": "rainny"}, {"temp" : 25, "weather": "sunny"}, {"temp" : 15, "weather": "storm"}]',
             "tuesday" ,'[{"temp" : 5, "weather": "winter"}, {"temp" : 10, "weather": "sun"}, {"temp" : 18, "weather": "dawn"}]'
            )as (day, type_of_day)
) --use your table instead of this CTE


select s.day, array(get_json_object(type_of_day_array[0],'$.temp'),
                    get_json_object(type_of_day_array[1],'$.temp'),
                    get_json_object(type_of_day_array[2],'$.temp')
                   ) as result_array --extract JSON elements and construct array
 from
(
select day,  split(regexp_replace(regexp_replace(type_of_day,'\\[|\\]',''),   --remove square brackets
                                  '\\}, *\\{','\\}##\\{'),                    --make convenient split separator
                   '##')                                                      --split                                  
          as type_of_day_array
  from your_table                                                             --use your table instead of this CTE
)s;

结果:

s.day   result_array    

monday  ["45","25","15"]    
tuesday ["5","10","18"] 

如果 JSON 的数组可以包含三个以上的元素,那么您可以使用 lateral viewexplode 或poseexplode,然后像下面的答案一样构建结果数组:https://stackoverflow.com/a/51570035/2700344

如果您需要 array<int> 而不是 array<string>,则将数组元素包装在 cast(... as int) 中:

cast(get_json_object(type_of_day[0],'$.temp') as int)... 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-14
    • 2014-11-30
    • 1970-01-01
    • 2010-12-21
    • 1970-01-01
    • 2020-07-10
    • 2023-04-03
    • 2021-10-21
    相关资源
    最近更新 更多