hive笔记:复杂数据类型-array结构

一、array结构

语法:array(val1,val2,val3,…) 

操作类型:array

array类型的数据可以通过'数组名[index]'的方式访问,index从0开始:

二、建表:

create external table  temp.array_20181101_v2 

( did string,

 meiti array<string>

)

ROW FORMAT DELIMITED FIELDS TERMINATED BY ' '

COLLECTION ITEMS TERMINATED BY ','(必须使)

LOCATION '/tmp/201810/array'

注意:

a.必须添加COLLECTION ITEMS TERMINATED BY ','若不添加,虽是array字段但结果不全,只有部分的meiti转换为array字段

b.'FIELDS TERMINATED BY' :字段与字段之间的分隔符

c.''COLLECTION ITEMS TERMINATED BY' :一个字段各个item的分隔符

三、查询方法或函数:

1.原表数据

 

2.array_contains():在字段类型为array中查找是否包含以及不包含某元素,在where后使用如:

%jdbc(hive)

select did,meiti

from temp.array_20181101_v2

where array_contains(meiti, '1118')

  and !array_contains(meiti, '1370')

 

3. lateral view explode (array)字段

%jdbc(hive)

select did,meiti

from temp.array_20181101_v2

lateral view explode(meiti) b1 as meiti1

group by id ,meiti1;

 

4.arraysplit的结合使用

(1)原数据格式

 

(2)array类型的数据可以通过'数组名[index]'的方式访问,index从0开始

注意:

  • customactionlabel[0]是string类型
  • 可以通过length(customactionlabel[0])>=1 判断是否为空
  • splite接受字符串类型,分解后为array类型

select cookie_id,customactionlabel,customactionlabel[0] as wcodes

from ad_bmw.sitemonitor

where  dt = '190831' and customactionlabel[0] is not null and customactionlabel[0]<>'' and customactionlabel[0]<>'[]'

and length(customactionlabel[0])>=2

customactionlabel[0]

 

select regexp_replace(split(customactionlabel[0],'\,')[0],'\[','') as v2

from ad_bmw.mid_sitemonitor_superid_khf_v2

注意:

  • split(customactionlabel[0],'\,')[0]是选取数组1-24162047001W2511169的但是结果含有一个'['
  • regexp_replace(split(customactionlabel[0],'\,')[0],'\[','')替换[为空。但是注意,[需要\转义 

问题:

 

原因如下:

如果customactionlabel[0]是字符串类型,包含很多空值。

但是数组中的空或者null的size=1,

同理split()空的数组后,在计算数据的长度也是1

可以使用一下语法:

select rg,sum(if(length(customactionlabel[0])==0,0,size(split(customactionlabel[0],","))))

from ad_bmw.sitemonitor

四、txt文件上传建表的格式问题

Txt文件应注意,保持数组的分隔符和前面几列的分隔符要不一样,并注意一下填写。

‘|’比较特殊,需要加转义符如,‘|’,若是‘;’,‘/’,‘,’或者空格则可以识别,

 

 

 

 

原文地址:https://www.cnblogs.com/sonia0087/p/9895349.html