Hive 撰寫 UDF 的門檻很低。這裡所說的 UDF 屬於 Temporary function(臨時函式),因此 Hive 版本需要在 0.4.0 以上才支援。開發時唯一要做的事,就是繼承 UDF 類別並重寫它的 evaluate 方法。
package com.hrj.hive.udf;
import org.apache.Hadoop.hive.ql.exec.UDF;
public class helloUDF extends UDF {
public String evaluate(String str) {
try {
return "HelloWorld " + str;
} catch (Exception e) {
return null;
}
}
}
把這個檔案編譯打包成 helloudf.jar,接著就能在 Hive CLI 中註冊使用:
hive> add jar helloudf.jar; hive> create temporary function helloworld as 'com.hrj.hive.udf.helloUDF'; hive> select helloworld(t.col1) from t limit 10; hive> drop temporary function helloworld;
1. 臨時函式的生命週期只在當前 session。因為 helloworld 是臨時函式,每次進入 Hive 都要重新執行 add jar 與 create temporary function。若想讓它長期可用,可以改用 CREATE FUNCTION 搭配永久函式,並把 jar 放到 Hive 能讀取的位置。
2. UDF 只能「多進一出」以外的其中一種。更精確地說:UDF 是「一進一出」的列處理函式;若需要多筆輸入聚合出一個結果(例如分組求和那類語意),就必須改為實作 UDAF;若是要一次吃進多個欄位、吐出多筆結果,則要寫 UDTF。