描述
- 自定義udf佃蚜,接收一個字段的每一個value,對應輸出轉(zhuǎn)換后的新value朴沿,與原value的關(guān)系是一對一
依賴
<dependency>
<groupId>org.apache.hive</groupId>
<artifactId>hive-exec</artifactId>
<version>${hive.version}</version>
<scope>provided</scope>
</dependency>
如果使用hadoop的writable類型返回拴袭,則另需添加依賴:
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-client</artifactId>
<version>${hadoop.version}</version>
<scope>provided</scope>
</dependency>
示例
// 假設處理邏輯為對兩個字段的值進行執(zhí)行四則運算
class MyUDF extends GenericUDF {
// 實現(xiàn)initialize方法雕薪,在對所有VALUE進行處理前的參數(shù)個數(shù)和類型校驗; arguments參數(shù)是指UDF函數(shù)調(diào)用時,sql語句中參數(shù)列表
override def initialize(arguments: Array[ObjectInspector]): ObjectInspector = {
if (arguments.length != 3) {
throw new UDFArgumentLengthException("arg: column1, column2, calcMethod")
}
// 根據(jù)UDF最后返回的值數(shù)據(jù)類型確定ObjectInspector的類型,通撑纤可以選擇java的類型或hadoop writable的類型
PrimitiveObjectInspectorFactory.javaIntObjectInspector
}
// 實現(xiàn)evaluate方法外傅,對每個value進行轉(zhuǎn)換并返回; arguments參數(shù)是指UDF函數(shù)調(diào)用時,table每一行傳入的值俩檬;返回值需要和initialize的返回類型對齊
override def evaluate(arguments: Array[GenericUDF.DeferredObject]): AnyRef = {
arguments(2).get().toString match {
case "+" => (arguments(0).get().toString.toInt + arguments(1).get().toString.toInt).asInstanceOf[java.lang.Integer]
case "-" => (arguments(0).get().toString.toInt - arguments(1).get().toString.toInt).asInstanceOf[java.lang.Integer]
case "*" => (arguments(0).get().toString.toInt * arguments(1).get().toString.toInt).asInstanceOf[java.lang.Integer]
case "/" => (arguments(0).get().toString.toInt / arguments(1).get().toString.toInt).asInstanceOf[java.lang.Integer]
case o => throw new UDFArgumentException(s"calcMethod should be +, - , * or /, got $o")
}
}
// 實現(xiàn)getDisplayString方法萎胰,對UDF進行描述
override def getDisplayString(children: Array[String]): String = {
"I am the plus method for hive"
}
}
部署
臨時UDF部署方法:
1. 打成jar包
2. 上傳至hive服務器
3. 在hive shell中執(zhí)行:add jar jar包路徑;
4. 在hive shell中執(zhí)行:create temporary function funtionName as '自定義UDF類路徑'
永久UDF部署方法:
1. 打成jar包
2. 上傳至hdfs
3. 在hive中進入需要用此UDF的庫中,執(zhí)行:create function funtionName as '自定義UDF類路徑' using jar 'jar包的hdfs路徑';
刪除永久UDF:
1. 在hive中進入需要刪除此UDF的庫中棚辽,執(zhí)行:drop function funtionName;