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 '\t'

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文件應注意,保持數組的分隔符和前面幾列的分隔符要不一樣,並注意一下填寫。

‘|’比較特殊,需要加轉義符如,‘\|’,若是‘;’,‘/’,‘,’或者空格則可以識別,

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM