如何在配置单元中创建结构的空数组?

o3imoua4  于 2021-06-24  发布在  Hive
关注(0)|答案(1)|浏览(401)

我可以看到 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?

mqkwyuun

mqkwyuun1#

你可以用 collect_list 或者 colect_set 对于收集从联接中获取的结构数组,并且联接条件为false,则collect\u 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   []

如果我尝试用不同的类型(例如array())合并struct的所有空数组,会发生什么情况:

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

例外情况:
编译语句时出错:失败:并集两侧的semanticexception架构应匹配:列my\ array是第一个表上的array类型,并且类型arraystructname:void,value:void在第二张table上。无法判断空ast的位置。
这说明第一个查询确实返回struct的空数组。您可以轻松地在查询中执行类似的连接。
如何在条件查询中使用它?演示:

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 a.id=b.id
group by a.id

case语句非常高兴,并且不会引发有关不兼容类型的异常

相关问题