1. 程式人生 > >Hive(15):自定義UDF

Hive(15):自定義UDF

一、使用者自定義函式分類

    1.UDF 使用者自定義格式轉化函式(一條資料輸入,一條資料輸出)
    2.udaf 使用者自定義聚合函式(多條資料輸入,一條資料輸出)
    3.udtf 使用者自定義**函式(一條資料輸入,多條資料輸出)

二、開發Java程式碼

1.新增pom依賴

   <dependency>  
      <groupId>org.apache.hadoop</groupId>  
      <artifactId>hadoop-client</artifactId>  
      <version>2.7.3</version>  
   </dependency> 
	<!-- https://mvnrepository.com/artifact/org.apache.hive/hive-exec -->
	<dependency>
	    <groupId>org.apache.hive</groupId>
	    <artifactId>hive-exec</artifactId>
	    <version>1.2.1</version>
	</dependency>
		<!-- Hive Client -->
	<dependency>
	    <groupId>org.apache.hive</groupId>
	    <artifactId>hive-jdbc</artifactId>
	    <version>1.2.1</version>
	</dependency>

2.java程式碼

package com.ibeifeng.hive.udf;

import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;

/**
 * 自定義函式
 */
public class TestHiveUDF_22 extends UDF {

	public Text evaluate(Text str,IntWritable flag){
		String value=str.toString();
		if(flag.get()==0){
			return new Text(value.toLowerCase());
		}else if(flag.get()==1) {
			return new Text(value.toUpperCase());
		}else {
			return new Text("flag引數異常");
		}
	
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println(new TestHiveUDF_22().evaluate(new Text("HAasd1OP"),new IntWritable(0)));
	}
}

3.Myeclipse打jar包

(1)選擇制定類檔案,右鍵-》Export    

(2)然後配置如下

(3)然後其他預設,finish結束

E:\Tools\WorkspaceforMyeclipse\JarPackage下面找到Hive_udf_2.jar

4.將自定義jar包與hive進行關聯

(1)新增打的jar包

add jar /opt/datas/Hive_udf_2.jar;
結果:
Added [/opt/datas/Hive_udf_2.jar] to class path
Added resources: [/opt/datas/Hive_udf_2.jar]

(2)建立函式方法

//在java檔案中,右鍵自己的class名稱,選擇copy qualified Name獲得路徑'com.ibeifeng.hive.udf.TestHiveUDF_22',如下圖

然後,建立函式

create temporary function my_udf as 'com.ibeifeng.hive.udf.TestHiveUDF_22';

(3)使用

select ename, my_udf(ename,0) low_ename from emp;
結果:
ename   low_ename
SMITH   smith
ALLEN   allen
WARD    ward
JONES   jones
MARTIN  martin
BLAKE   blake
CLARK   clark
SCOTT   scott
KING    king
TURNER  turner
ADAMS   adams
JAMES   james
FORD    ford
MILLER  miller

(4)建立永久udf

需要把jar包上傳到hdfs上,然後就可以
-》上傳

dfs -put /opt/datas/Hive_udf_2.jar /;

-》載入

create function my_udf_hdfs as 'com.ibeifeng.hive.udf.TestHiveUDF_22' using jar 'hdfs://bigdata.ibeifeng.com:8020/Hive_udf_2.jar';

-》關閉hive客戶端
-》重新開啟hive

bin/hive

-》執行

select ename, my_udf_hdfs(ename,0) low_ename from emp;
成功:
ename   low_ename
SMITH   smith
ALLEN   allen
WARD    ward
JONES   jones
MARTIN  martin
BLAKE   blake
CLARK   clark
SCOTT   scott
KING    king
TURNER  turner
ADAMS   adams
JAMES   james
FORD    ford
MILLER  miller