zl程序教程

您现在的位置是:首页 >  数据库

当前栏目

HIVE中关于collect_set与explode函数妙用

2023-03-09 22:30:37 时间

hive的复合数据类型

Hive中的列支持使用三类复杂的集合数据类型,即:array,map及struct,这些类型的名称是保留字,具体用法可参见该篇博文,里面有关于三类基本集合数据类型的操作实例,注:map中可嵌套array类型。

例如,定义表:

  1. create table example ( 
  2.     device_id string, 
  3.     login_ip array<string>, 
  4.     user_info map<string,array<string>> 
  5.     address struct<street:string,city:string,state:string> 
  6. row format delimited 
  7. fields terminated by '\001' 
  8. collection items terminated by '\002' 
  9. map keys terminated by '\003' 
  10. lines terminated by '\n' 
  11. stored as RCFile; 

假设这样的数据类型以分区表存储,你要统计一段时间类no=1下的去重score,那么该怎么办了?这里可配合使用lateral view首先实现列转行的功能,如下所示:

select no,score from tablaa lateral view explode(score_set) xxx as score;

注:xxx代表虚表名称,不能缺少。

进一步深化上述代码解决统计一段时间的去重值,可写为:

select no,collect_set(score) from tablaa lateral view explode(score_set) xxx as score group by no;

这样,将两个函数结合实现了行转列或列转行的妙用。