Vol08 Hive中的行列互轉 與UDTF的應用

2021-09-27 05:57:44 字數 1914 閱讀 8159

udtf(user-definedtable-generating functions) 用來解決輸入一行輸出多行(on-to-manymaping) 的需求。

hive 官方提供的所有udtf請參照官方文件,

本文主要以我們日常用到較多的explode 為例說明。

udtf有兩種使用方法,一種直接放到select後面(不常用,基本不用),一種和lateral view一起使用(常用)。

1.直接select中使用

select explode(mycol) as mynewcolfrom mytable;

說明:其中mycol 為陣列型別,mytable 表資料如下:

[100,200]

[300,400]

經過udtf處理,查詢結果為:

單獨使用此函式有一定的侷限性,不太適用我們日常需求的場景,如下:

a)      不可以與其他字段一起使用:如 select ,type,explode(mycol) asmynewcol from mytable ; 這樣是不支援的。

b)      不可以巢狀呼叫:如 select explode(explode(mycol)) asmynewcol from src ; 這樣是不支援的。

c)      不可以和group by/cluster by/distribute by/sort by一起使用:如 select explode(mycol) as mynewcol from src group by mynewcol 這樣是不支援的。

2.和lateral view一起使用

select col1,col2,newcolfrom mytable lateral view explode(mycol) adtable as newcol

說明:此方法更為常用,滿足我們日常需求。

執行過程相當於單獨執行了兩次抽取,然後union到乙個表裡,但job數只有乙個。

同樣mycol 也需要為陣列型別,但日常中我們多數情況下是string 型別經過split 函式拆分後獲取陣列型別 。

mytable 表資料如下:

id user name all_citys

'id1', 'user1', 'name1', '北京,天津'

'id2', 'user2', 'name2', '上海,河北'

執和語句:select id,user,name,city from mytable lateral view explode(split(all_citys,',')) adtableas city

經過udtf處理,查詢結果為:

id user name city

'id1', 'user1', 'name1', '北京'

'id1', 'user1', 'name1', '天津'

'id2', 'user2', 'name2', '上海'

'id2', 'user2', 'name2', '河北'

避免了使用 union all 多個job進行多次讀取占用較多資源的情況。

注意:新生的新列別名一定要與select 後讀取的列名保持一致。

explode 生成的新列一定要放在所有列之後。

實際應用中可靈活使用,包括與其它函式巢狀使用,以及自定義陣列資料格式。

另:自 hive 0.13.0 版本支援 po***plode 函式,與 explode 的區別是新增支援位置序列可自動生成為單獨一列

mytable 表資料如下:

[100,200]

[300,400]

經過udtf處理,查詢結果為:

1,100

2,200

1,300

2,400

Hive中的兩種行列轉換

2.字串合併與拆分形式的行列轉換 總結資料如下 name item score 張三 數學 58 張三 英語 83 張三 語文 89 李四 數學 67 李四 英語 35 李四 語文 92 王五 數學 75 王五 英語 88 王五 語文 70 要求將每個人各科成績打在一行上,分成三列顯示,即,目標資料...

hive 中時間戳與時間字串的相互轉換

時間戳是資料庫常用的存放日期的形式之一,表示從 utc 時間 1970 01 01 00 00 00 開始到現在的秒數,與常規時間格式如 2018 01 01 00 00 00 可以相互轉換,方法如下。一 unix timestamp 函式用法 1 unix timestamp 返回當前時間戳。另外...

numpy與tensor中的陣列互轉

如 import torch as t import numpy as np x t.ones 5 float tensor型別為floattensor,也可呼叫long 方法轉為longtensor y x.numpy print x print y 輸出 tensor 1.1.1.1.1.1.1...