教育行業(yè)A股IPO第一股(股票代碼 003032)

全國咨詢/投訴熱線:400-618-4000

什么是內置函數?什么是用戶定義函數?

更新時間:2023年01月03日14時46分 來源:傳智教育 瀏覽次數:

好口碑IT培訓

Hive的函數分為兩大類:內置函數(Built-in Functions)、用戶定義函數UDF(User-Defined Functions):

 內置函數可分為:數值類型函數、日期類型函數、字符串類型函數、集合函數、條件函數等;

 用戶定義函數根據輸入輸出的行數可分為3類:UDF、UDAF、UDTF。

1672386890978_81.png

用戶定義函數UDF分類標準, 可以根據函數輸入輸出的行數劃分:

UDF(User-Defined-Function)普通函數,一進一出。

UDAF(User-Defined Aggregation Function)聚合函數,多進一出。

UDTF(User-Defined Table-Generating Functions)表生成函數,一進多出。

UDF分類標準本來針對的是用戶自己編寫開發(fā)實現的函數。UDF分類標準可以擴大到Hive的所有函數中:包括內置函數和用戶自定義函數。

因為不管是什么類型的函數,一定滿足于輸入輸出的要求,那么從輸入幾行和輸出幾行上來劃分沒有任何問題。千萬不要被UD(User-Defined)這兩個字母所迷惑,照成視野的狹隘。比如Hive官方文檔中,針對聚合函數的標準就是內置的UDAF類型。

1672387136499_83.png

內置函數(build-in)指的是Hive開發(fā)實現好,直接可以使用的函數,也叫做內建函數。內置函數根據應用歸類整體可以分為8大種類型,我們將列舉其中重要的,使用頻率高的函數的進行詳細講解。

(1)String Functions 字符串函數

•字符串長度函數:length
•字符串反轉函數:reverse
•字符串連接函數:concat
•帶分隔符字符串連接函數:concat_ws
•字符串截取函數:substr,substring
------------String Functions 字符串函數------------
select length("itcast");
select reverse("itcast");
select concat("angela","baby");
--帶分隔符字符串連接函數:concat_ws(separator, [string | array(string)]+)
select concat_ws('.', 'www', array('itcast', 'cn'));
--字符串截取函數:substr(str, pos[, len]) 或者substring(str, pos[, len])
select substr("angelababy",-2); --pos是從1開始的索引,如果為負數則倒著數select substr("angelababy",2,2);
--分割字符串函數: split(str, regex)
select split('apache hive', ' ');

(2)Date Functions 日期函數

-----------Date Functions 日期函數-----------------
--獲取當前日期: current_date
select current_date();
--獲取當前UNIX時間戳函數: unix_timestamp
select unix_timestamp();
--日期轉UNIX時間戳函數: unix_timestamp
select unix_timestamp("2011-12-07 13:01:03");
--指定格式日期轉UNIX時間戳函數: unix_timestamp
select unix_timestamp('20111207 13:01:03','yyyyMMdd HH:mm:ss');
--UNIX時間戳轉日期函數: from_unixtime
select from_unixtime(1618238391);
select from_unixtime(0, 'yyyy-MM-dd HH:mm:ss');
--日期比較函數: datediff  日期格式要求'yyyy-MM-dd HH:mm:ss' or 'yyyy-MM-dd'select datediff('2012-12-08','2012-05-09');
--日期增加函數: date_add
select date_add('2012-02-28',10);
--日期減少函數: date_sub
select date_sub('2012-01-1',10);
----Mathematical Functions 數學函數-------------
--取整函數: round  返回double類型的整數值部分(遵循四舍五入)
select round(3.1415926);
--指定精度取整函數: round(double a, int d) 返回指定精度d的double類型select round(3.1415926,4);
--取隨機數函數: rand 每次執(zhí)行都不一樣返回一個0到1范圍內的隨機數select rand();
--指定種子取隨機數函數: rand(int seed) 得到一個穩(wěn)定的隨機數序列
select rand(3);

(4)Conditional Functions 條件函數

主要用于條件判斷、邏輯判斷轉換這樣的場合

-----Conditional Functions 條件函數------------------
--使用之前課程創(chuàng)建好的student表數據
select * from student limit 3;
--if條件判斷: if(boolean testCondition, T valueTrue, T valueFalseOrNull)
select if(1=2,100,200);
select if(sex ='男','M','W') from student limit 3;
--空值轉換函數: nvl(T value, T default_value)
select nvl("allen","itcast");
select nvl(null,"itcast");
--條件轉換函數: CASE a WHEN b THEN c [WHEN d THEN e]* [ELSE f] END 
select case 100 when 50 then 'tom' when 100 then 'mary' else 'tim' end;
select case sex when '男' then 'male' else 'female' end from student limit 3;

0 分享到:
和我們在線交談!