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

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

我可以看到 Hive 1.1.0 ,它应根据条件返回空数组或 struct<name: string, jobslots: int> 这是我的密码:

  1. select
  2. case when <condition>
  3. then array()
  4. else array(struct(t1.name, t1.jobslots))
  5. end
  6. 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的数组:

  1. select a.id, size(collect_list(b.str))=0 array_size_zero
  2. from
  3. (select 2 id ) a
  4. left join (select 1 as id, named_struct('name',null,'value',null) as str) b
  5. on a.id=b.id
  6. group by a.id

结果:

  1. a.id array_size_zero
  2. 2 true

如果您将第一个子查询a中的id更改为与b联接,它将返回一个包含1个元素的数组。而且这些结果都是同一类型的,您可以使用union all轻松地进行检查。
检查结果类型相同:

  1. select a.id, collect_list(b.str) my_array
  2. from
  3. (select 1 id ) a
  4. left join (select 1 as id, named_struct('name',null,'value',null) as str) b
  5. on a.id=b.id
  6. group by a.id
  7. union all
  8. select a.id, collect_list(b.str) my_array
  9. from
  10. (select 2 id ) a
  11. left join (select 1 as id, named_struct('name',null,'value',null) as str) b
  12. on a.id=b.id
  13. group by a.id

结果:

  1. id my_array
  2. 1 [{"name":null,"value":null}]
  3. 2 []

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

  1. select 1 id, array() my_array
  2. union all
  3. select a.id, collect_list(b.str) my_array
  4. from
  5. (select 2 id ) a
  6. left join (select 1 as id, named_struct('name',null,'value',null) as str) b
  7. on a.id=b.id
  8. group by a.id

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

  1. select a.id, case when true --Put your condition here instead of dummy <true>
  2. then collect_list(a.str) --not empty
  3. else collect_list(b.str) --this one is empty array of the same type
  4. end as my_array
  5. from
  6. (select 2 id, named_struct('name',null,'value',null) str) a
  7. left join (select 1 as id, named_struct('name',null,'value',null) as str) b
  8. on a.id=b.id
  9. group by a.id

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

展开查看全部

相关问题