【问题标题】:Preserve order while converting string array into int array in hive在 hive 中将字符串数组转换为 int 数组时保留顺序
【发布时间】:2021-08-31 11:57:47
【问题描述】:

我正在尝试通过保持原始顺序将字符串数组转换为 int 数组 这是我的数据的示例:

id       attribut                       string_array
id1      attribut1, 10283:990000       ["10283","990000"]
id2      attribut2, 10283:36741000     ["10283","36741000"]
id3      attribut3, 10283:37871000     ["10283","37871000"]
id4      attribut4, 3215:90451000      ["3215","90451000"]

这是我如何将字段“string_array”转换为整数数组

select  
id, 
attribut,
string_array,
collect_list(cast(array_explode as int)),
from table
lateral view outer explode(string_array) r as array_explode

它给了我:

id       attribut                        string_array              int_array
id1      attribut1,10283:990000         ["10283","990000"]        [990000,10283]
id2      attribut2,10283:36741000       ["10283","36741000"]      [10283,36741000]
id3      attribut3,10283:37871000       ["10283","37871000"]      [37871000,10283]
id4      attribut4,3215:90451000        ["3215","90451000"]       [90451000,3215]

如您所见,“字符串数组”中的顺序没有保留在“int_array”中,我需要它与“string_array”中的完全相同。 有谁知道如何做到这一点?

任何帮助将不胜感激

【问题讨论】:

    标签: arrays hive type-conversion hiveql collect


    【解决方案1】:

    对于 Hive:使用poseexplode,在collect_list 之前的子查询中按位置排序按id 进行分发

    select  
    id, 
    attribut,
    string_array,
    collect_list(cast(element as int)),
    from
    (select * 
      from table t
           lateral view outer posexplode(string_array) e as pos,element 
      distribute by t.id, attribut, string_array -- distribute by group key
      sort by pos        -- sort by initial position
    ) t
    group by id, attribut, string_array
    

    另一种方法是从您的属性中提取子字符串并在不爆炸的情况下拆分(正如您在评论中询问的那样)

    select split(regexp_extract(attribut, '[^,]+,(.*)$',1),':')
    

    正则表达式'[^,]+,(.*)$'表示:

    [^,]+ - 不是逗号 1 次以上 , - 逗号 (.*)$ - 在逗号之后捕获第 1 组中的所有其他内容,直到字符串结尾

    演示:

    select split(regexp_extract('attribut3,10283:37871000', '[^,]+,(.*)$',1),':')
    

    结果:

    ["10283","37871000"]
    

    【讨论】:

    • 感谢@leftjoin 的回复,但这不起作用,我完全随机,有时会保持原始顺序,有时则不会。另外,当我从 attributes 字段中提取带有 regex_extractsplit 的 string_array 字段时,您知道将提取为字符串格式而不是字符串数组的更简单方法吗?示例:从 attributes attribut3,10283:37871000 字段的这个值提取 10283,37871000 而不是 ["10283","37871000"] ?
    • @Stella 回答,您可以从最后一个查询中删除拆分以获取子字符串 10283,37871000。像这样: regexp_extract(attribute, '[^,]+,(.*)$',1)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-26
    • 1970-01-01
    • 1970-01-01
    • 2016-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多