gpt4 book ai didi

sql - 如何在 hive 中创建一个空的结构数组?

转载 作者:行者123 更新时间:2023-12-01 04:56:08 34 4
gpt4 key购买 nike

我在 Hive 1.1.0 有意见,根据条件,它应该返回一个空数组或一个数组 struct<name: string, jobslots: int>这是我的代码:

select
case when <condition>
then array()
else array(struct(t1.name, t1.jobslots))
end
from table t1;
这里的问题是,空数组 array()类型为 array<string> .因此,当我尝试将其插入表中时,它会引发错误。
如何更改它以返回类型为 array<struct<name: string, jobslots:int>> 的空数组以便 Hive's size()函数在这个数组上返回 0?

最佳答案

你可以使用 collect_listcolect_set用于收集从连接中获取的结构数组,并且连接条件为假,则 collect_list 将生成一个空的结构数组。
此查询返回大小为 0 的数组:

select a.id, size(collect_list(b.str))=0 array_size_zero
from
(select 2 id ) a
left join (select 1 as id, named_struct('name',null,'value',null) as str) b
on a.id=b.id
group by a.id
结果:
a.id    array_size_zero
2 true
如果在第一个子查询 a 中更改 id 以与 b 连接,它将返回具有 1 个元素的数组。并且这些结果是相同类型的,您可以使用 union all 轻松检查它。
检查结果类型相同:
select a.id, collect_list(b.str) my_array
from
(select 1 id ) a
left join (select 1 as id, named_struct('name',null,'value',null) as str) b
on a.id=b.id
group by a.id

union all

select a.id, collect_list(b.str) my_array
from
(select 2 id ) a
left join (select 1 as id, named_struct('name',null,'value',null) as str) b
on a.id=b.id
group by a.id
结果:
id  my_array
1 [{"name":null,"value":null}]
2 []
如果我尝试 UNION ALL 不同类型的空结构数组会发生什么,例如 array():
select 1 id, array() my_array

union all

select a.id, collect_list(b.str) my_array
from
(select 2 id ) a
left join (select 1 as id, named_struct('name',null,'value',null) as str) b
on a.id=b.id
group by a.id
异常(exception):

Error while compiling statement: FAILED: SemanticException Schema ofboth sides of union should match: Column my_array is of typearray on first table and typearray<structname:void,value:void> on second table. Cannot tell theposition of null AST.


这表明第一个查询确实返回空的结构数组。
您可以轻松地在查询中执行类似的连接。
如何在带条件的查询中使用它?
演示:
select a.id, case when true --Put your condition here instead of dummy <true> 
then collect_list(a.str) --not empty
else collect_list(b.str) --this one is empty array of the same type
end as my_array
from
(select 2 id, named_struct('name',null,'value',null) str) a
left join (select 1 as id, named_struct('name',null,'value',null) as str) b
on FALSE
group by a.id
CASE 表达式很高兴并且不会引发关于不兼容类型的异常

关于sql - 如何在 hive 中创建一个空的结构数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56016700/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com