2、編寫UDF函數的時候需要注意一下幾點:
a)自定義UDF需要繼承org.apache.hadoop.hive.ql.UDF。
b)需要實現evaluate函數,evaluate函數支持重載。
3、步驟
a)把程序打包放到目標機器上去;
b)進入hive客戶端,添加jar包:hive>add jar /run/jar/udf_test.jar;
c)創建臨時函數:hive>CREATE TEMPORARY FUNCTION add_example AS 'hive.udf.Add';
d)查詢HQL語句:
SELECT add_example(8, 9) FROM scores;
SELECT add_example(scores.math, scores.art) FROM scores;
SELECT add_example(6, 7, 8, 6.8) FROM scores;
e)銷燬臨時函數:hive> DROP TEMPORARY FUNCTION add_example;
4、案列
類NationUDF
package edu.jianwei.hive.udf;
import java.util.HashMap;
import java.util.Map;
import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.hadoop.io.Text;
public class NationUDF extends UDF{
private static Map<String, String> areaMap = new HashMap<String, String>();
static {
areaMap.put("China", "中國");
areaMap.put("Japan", "日本");
areaMap.put("USA", "美國");
}
public Text evaluate(Text in){
String result = areaMap.get(in.toString());
if(result == null){
result = "其他";
}
return new Text(result);
}
}
自定義函數調用過程:1.添加jar包(在hive命令行裏面執行)
hive> add jar /root/NUDF.jar;
2.創建臨時函數
hive> create temporary function getNation as 'edu.jiawei.hive.udf.NationUDF';
3.調用
hive> select id, name, getNation(nation) from people;
4.將查詢結果保存到HDFS中
hive> create table result row format delimited fields terminated by '\t' as select * from people order by id desc;