UDF介紹及編程要點
Hive中自帶了許多函數(shù)碟渺,方便數(shù)據(jù)的處理分析。但是有時候沒有內(nèi)部的函數(shù)來提供想要的功能突诬,需要自定義函數(shù)(UDF)來實現(xiàn)想要的功能苫拍。
編寫UDF需要下面兩個步驟
- 繼承org.apache.hadoop.hive.ql.UDF
- 實現(xiàn)evaluate函數(shù),這個函數(shù)必須要有返回值旺隙,不能設(shè)置為void绒极。同時建議使用mapreduce編程模型中的數(shù)據(jù)類型(Text,IntWritable等),因為hive語句會被轉(zhuǎn)換為mapreduce任務(wù)催束。
針對具體問題實現(xiàn)UDF步驟
- 首先配置eclipse環(huán)境集峦。創(chuàng)建maven項目后,在pom.xml中添加依賴。
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<hadoop.version>2.5.0</hadoop.version>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-client</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>org.apache.hive</groupId>
<artifactId>hive-jdbc</artifactId>
<version>0.13.1</version>
</dependency>
<dependency>
<groupId>org.apache.hive</groupId>
<artifactId>hive-exec</artifactId>
<version>0.13.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
-
針對實際問題分析需求
需求: 去除下列數(shù)據(jù)字段中的雙引號
hive1.png - 編寫UDF代碼及本地測試
import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.hadoop.io.Text;
/*
* 去除字符串中的雙引號
*/
public class signUDF extends UDF {
public Text evaluate(Text string) {
// 過濾
if (null == string) {
return null;
}
// 用來保存最后結(jié)果
Text result;
// 替換字符串的雙引號為空
String s = string.toString().replaceAll("\"", "");
// 用中間結(jié)果生成返回值
result = new Text(s);
return result;
}
}
測試如下
輸入:"wulei" "www"
輸出:wulei www
- 打成jar包在hive中測試
-
打成jar包上穿至Linux中
hive3.png - 關(guān)聯(lián)jar包
hive (default)> add jar /opt/datas/signuUDF.jar;
Added /opt/datas/signuUDF.jar to class path
Added resource: /opt/datas/signuUDF.jar
- 創(chuàng)建方法(退出hive shell后將失效)
hive (default)> create temporary function my_udf as "hiveUDF.hiveUDF.signUDF";
OK
Time taken: 0.039 seconds
- 永久添加UDF的方法:配置hive-site.xml文件中的hive.aux.jars.path(輔助jar路徑)屬性塔淤,屬性值為jar包的絕對路徑
- 驗證自定義函數(shù)
hive (test_db)> select * from test1;
OK
test1.ip test1.source
"192.168.200.5" "/wulei/in"
"192.168.200.4" "/wulei/out"
hive (test_db)> select my_udf(ip) from test1;
MapReduce Jobs Launched:
Job 0: Map: 1 Cumulative CPU: 1.7 sec HDFS Read: 276 HDFS Write: 28 SUCCESS
Total MapReduce CPU Time Spent: 1 seconds 700 msec
OK
_c0
192.168.200.5
192.168.200.4
Time taken: 41.616 seconds, Fetched: 2 row(s)