Hive自定義函式(UDF)的編寫及使用
前提條件:
1. 安裝好hadoop2.7.3(LInux環境下)
2. 安裝好Hive2.3.3,參考:Hive的安裝配置
3. 安裝好Maven(Windows環境下)參考:Maven安裝
4. 安裝好eclipse(Windows環境下)
Hive自定義函式(UDF),UDF是user-defined function的簡寫。雖然Hive內建了許多函式供使用,但有時還是滿足不了我們實際專案開發的需求,可通過編寫自定義函式滿足這一需求。
該如何編寫和使用Hive的自定義函式呢?
1.建立Maven工程:myhive
2.編輯pom.xml,在</dependencies>之前新增如下語句:
<dependency> <groupId>org.apache.hive</groupId> <artifactId>hive-exec</artifactId> <version>2.3.3</version> </dependency> <dependency> <groupId>org.apache.hadoop</groupId> <artifactId>hadoop-common</artifactId> <version>2.7.3</version> </dependency>
3.新建自定義函式類
MyConcatString.java
4.編寫程式碼:
package com.myhive;
import org.apache.hadoop.hive.ql.exec.UDF;
public class MyConcatString extends UDF{
//必須重寫一個方法,方法的名字必須叫:evaluate
public String evaluate(String a,String b){
return a+"*******"+b;
}
}
5.打包工程:
複製工程所在路徑:右鍵工程-->Properties-->Resource-->找到location,複製E:\EclipsePro\Hive\myhive
在cmd下切換到工程所在目錄:
切換到E盤:>e:
e:
切換到工程目錄:> cd E:\EclipsePro\Hive\myhive
cd E:\EclipsePro\Hive\myhive
執行打包命令:
mvn clean package
打包成功出現如下圖:
6.上傳打包生產的jar檔案到Linux目錄下
這裡使用winscp工具上傳:
Linux的ls命令檢視已上傳成功,如下圖:
$ ls
7. 進入hive命令列
$ hive
8. 新增自定義函式的jar檔案到hive的類路徑:
hive> add jar /home/hadoop/jarfile/myhive-0.0.1-SNAPSHOT.jar;
9. 使用使用者自定義的函式建立一個臨時函式:
hive> create temporary function myconcat as 'com.myhive.MyConcatString';
10. 測試資料準備:
建立一張hive託管表t1表:
hive> create table t1(ename string, mgr string) row format delimited fields terminated by ',';
開啟一個新的終端,在Linux系統下新建一個test.txt檔案
$ nano test.txt
$ nano test.txt
填入以下內容:
hello,word
hello,hadoop
hello,hive
儲存,退出。
回到hive命令列,將test.txt的內容載入到輸入t1表:
hive> load data local inpath '/home/hadoop/jarfile/test.txt' into table t1;
注意:/home/hadoop/jarfile/test.txt為test.txt的絕對路徑,需要根據實際情況修改。
檢視t1表內容:
hive> select * from t1;
輸出內容如下:
OK
hello word
hello hadoop
hello hive
Time taken: 4.614 seconds, Fetched: 3 row(s)
11. 使用Hive自定義函式:
hive> select myconcat(ename,mgr) from t1;
輸出內容如下:
OK
hello*******word
hello*******hadoop
hello*******hive
Time taken: 1.661 seconds, Fetched: 3 row(s)
hive>
如上輸出了用******來拼接兩個字串,說明已經成功編輯及使用了Hive自定義函式。
完成! enjoy it!