Hadoop Hive概念學習系列之hive里的用戶定義函數UDF(十七)


  Hive可以通過實現用戶定義函數(User-Defined Functions,UDF)進行擴展(事實上,大多數Hive功能都是通過擴展UDF實現的)。想要開發UDF程序,需要繼承org.apache.hadoop.ql.exec.UDF類,並重載evaluate方法。Hive API提供@Description聲明,使用聲明可以在代碼中添加UDF的具體信息。在Hive中可以使用DESCRIBE語句來展現這些信息。

  Hive的源碼本身就是編寫UDF最好的參考資料。在Hive源代碼中很容易就能找到與需求功能相似的UDF實現,只需要復制過來,並加以適當的修改就可以滿足需求。

 

 

 

 

下面是一個具體的UDF例子,該例子的功能是將字符串全部轉化為小寫字母

package com.madhu.udf;

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

//add jar samplecode.jar;
//create temporary function to_upper as 'com.madhu.udf.UpercaseUDF';
@Desription(
  name="to_upper",
  value="_FUNC_(str) -Converts a string to uppercase",
  extended="Example:\n" +
  " > select to_upper(producer) from videos_ex;\n" +
  " JOHN MCTIERNAN"
)
public class UpercaseUDF extends UDF{
  public Text evaluate(Text input){
    Text result = new Text("");
    if (input != null){
      result.set(input.toString().toUpperCase());
    }  
    return result;
  }
}

 

 

   UDF只有加入到Hive系統路徑,並且使用唯一的函數名注冊后才能在Hive中使用。UDF應該被打成JAR包。

 

 上傳打好的 samplecode.jar,然后如下

 

 

下面的語句可以把JAR條件放入Hive系統路徑,並注冊相關函數:

hive > add jar samplecode.jar          這個目錄,根據自己的情況而定
Added samplecode.jar to class path
Added resource:samplecode.jar
hive> create temporary function to_upper as 'com.madhu.udf.UppercaseUDF';

 

 

  現在可以在Hive中使用這個函數了:

hive > describe function to_upper;
OK
to_upper(str) -Converts a string to uppercase
Time taken:0.039 seconds,Fetched:1 row(s)
hive > describe function extended to_upper;
OK
to_upper(str) - Converts a string to uppercase
Example:
> select to_upper(producer) from videos_ex;
JOHN MCTIERNAN
Time taken:0.07 seconds,Fetched:4 row(s)

 

 

 

  手動的話,見

3 hql語法及自定義函數 + hive的java api

  

  自動的話,見

Hive項目開發環境搭建(Eclipse\MyEclipse + Maven)

 

 

 

 

 

 

 

 

 

 

  這里,我自己寫了一個hiveEvaluateUDF 自定義函數,實現某一個我們自己想要的功能。比如,我這里是轉換功能。開始編寫代碼

package cn.itcast.bigdata;

import org.apache.hadoop.hive.ql.exec.UDF;

public class hiveEvaluateUDF extends UDF{
public String evaluate(String str){
if (str == null | str.toString().isEmpty()){
return new String();
}
return str.trim().toLowerCase();
}

}

 

 

 

hive> add jar hiveEvaluateUDF.jar;  

 

得到 cn.itcast.bigdata.hiveEvaluateUDF

 

hive> create temporary function to_lower as 'cn.itcast.bigdata.hiveEvaluateUDF';

 

  剩下的,自行去嘗試。

 

 

 

 

 

 

如何用好自己寫好的自定義UDF函數

方法一:

  比如,我這里,有個轉大寫的自定義UDF函數,自己寫個vi hiveupperrc文件。每次執行這個文件,這個自定義的轉大寫函數能用了。

 

方法二:

在$HIVE_HOME/scripts目錄下,寫個如 hiveupperrc.sh腳本。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM