我們知道數(shù)倉(cāng)不滿足第一范式,也就是說(shuō)數(shù)倉(cāng)中的字段是可再分的,不滿足原子性,即DDL可以定義一個(gè)字段類型為數(shù)組。因此才有了explode()函數(shù),用于給這個(gè)字段展開降維。
explode()可以把指定的數(shù)組字段拆分降維展開為多行。類似于UDTF函數(shù),作用于單/多個(gè)數(shù)據(jù)行,并且產(chǎn)生多個(gè)數(shù)據(jù)行,以一個(gè)表作為輸出。
explode()用法:
-- array是數(shù)組字段 也可以是split()函數(shù)
select explode(array) from tablename
但這樣無(wú)法同時(shí)查詢多列,即select name,explode(array) from table會(huì)報(bào)錯(cuò)。
原因時(shí)當(dāng)使用UDTF函數(shù)的時(shí)候,Hive只允許對(duì)拆分字段進(jìn)行訪問(wèn)。
要同時(shí)查詢多列只能:
select t.item, t.* from tablename t
lateral view explode(array) t as item
lateral view explode() 是把要拆分的字段array拆分后以多行存儲(chǔ)在t表中的item字段中(當(dāng)然也可以另起一個(gè)臨時(shí)表)。
注意lateral view explode()執(zhí)行順序是在from之后where之前,與join on同時(shí)執(zhí)行,所以要緊跟在from語(yǔ)句后。
如果一行數(shù)據(jù)有兩列需要炸裂展開,可以這樣寫:
select t.item1, t.item2, t.* from tablename t
lateral view explode(array1) t as item1
lateral view explode(array2) t as item2
這樣得到的行數(shù)是 n * length(array1) * length(array2)