Hive進行UDF開發十分簡單,此處所說UDF為Temporary的function,所以需要hive版本在0.4.0以上才可以。
Hive的UDF開發只需要重構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;
}
}
}
將該java文件編譯成helloudf.jar
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.helloworld為臨時的函數,所以每次進入hive都需要add jar以及create temporary操作
2.UDF只能實現一進一出的操作,如果需要實現多進一出,則需要實現UDAF
轉自: http://www.cnblogs.com/end/archive/2012/10/12/2721543.html
除此之外,我們也可以創建非臨時的UDF,然后將其部署到服務器上。
1 編寫UDF類
以簡單的處理單個字段的UDF函數為例,開發自定義UDF函數需要繼承’org.apache.hadoop.hive.ql.exec.UDF’類.
可以通過Maven添加,pom文件中加入(版本號跟Hive版本一致即可):
<dependency> <groupId>org.apache.hive</groupId> <artifactId>hive-exec</artifactId> <version>0.13.1</version> </dependency>
最簡單的實現只需繼承UDF類,並實現evaluate函數.如下UDF函數用來將IP(v4)地址轉換為整數.
package com.liam8.hive;
import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.exec.UDF;
/**
* Convert IPv4 to a num which type is Long in java.
* Created by Liam on 2016/4/11.
*/
@Description(name = "IpToNum", value = "_FUNC_(ip) - Convert IPv4 to a num(long).")
public class IpToNum extends UDF {
public long evaluate(String ip) {
String[] nums = ip.split("\\.");
return Long.parseLong(nums[3]) + Long.parseLong(nums[2]) * 256
+ Long.parseLong(nums[1]) * 65536 + Long.parseLong(nums[0]) * 16777216;
}
}
evaluate方法的輸入輸出即是UDF函數的輸入輸出.
Description注解部分提供函數的幫助信息.
執行:desc function test.iptonum
輸出:
test.iptonum(ip) - Convert IPv4 to a num(long).
源碼已上傳 Github
2 部署及創建UDF函數
PS:Hive0.13及以后版本適用
部署jar包
將jar包復制到HDFS.
hdfs -dfs -put udfs-0.1.jar 'hdfs:///user/hadoop/hiveUDF'
創建永久函數
需在Hive中執行sql語句,格式如下:
CREATE FUNCTION [db_name.]function_name AS class_name [USING JAR|FILE|ARCHIVE 'file_uri' [, JAR|FILE|ARCHIVE 'file_uri'] ];
如:
create function test.iptonum as 'com.liam8.hive.IpToNum' using jar 'hdfs:///user/hadoop/hiveUDF/udfs-0.1.jar'
函數需要屬於某個庫,如這里是’test’,當其他庫調用時,需要加上庫名,如’test.iptonum’.
調用方式: select test.iptonum('127.0.0.1');
創建臨時函數
臨時函數只在當前session中有效,臨時函數不能指定庫.
create temporary function iptonum as 'com.liam8.hive.IpToNum' using jar 'hdfs:///user/hadoop/hiveUDF/udfs-0.1.jar'
調用方式: select iptonum('127.0.0.1');
4 參考資料
LanguageManualDDL-PermanentFunctions
原文地址:http://liam8.ml/2016/04/11/add-udf-to-hive/
版權聲明:轉載請注明出處:http://blog.csdn.net/liam08
