1. 程式人生 > >hive 自定義函式UDF

hive 自定義函式UDF

1. 在Hive中給我們內建了很多函式

進入hive客戶端,檢視hive內建函式:

hive > show functions;

OK ! != % & * + - / < <= <=> <> = == > >= ^ abs acos add_months and array

...

 檢視函式的具體方法:

hive> DESCRIBE FUNCTION case; OK CASE a WHEN b THEN c [WHEN d THEN e]* [ELSE f] END - When a = b, returns c; when a = d, return e; else return f

hive> DESCRIBE FUNCTION EXTENDED case;

hive> DESCRIBE FUNCTION EXTENDED case; OK CASE a WHEN b THEN c [WHEN d THEN e]* [ELSE f] END - When a = b, returns c; when a = d, return e; else return f Example:  SELECT  CASE deptno    WHEN 1 THEN Engineering    WHEN 2 THEN Finance    ELSE admin  END,  CASE zone    WHEN 7 THEN Americas    ELSE Asia-Pac  END  FROM emp_de tails

2. hive函式除了內建還可以自定義

自定義函式開發UDF: 1. 使用maven建立一個java專案 2. 繼承UDF類; 3. 重寫evaluate方法

建立一個UrlDecodeWithChar類繼承UDF,並且重寫evaluate方法

import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import org.apache.hadoop.hive.ql.exec.UDF; import org.apache.hadoop.io.Text;

public class UrlDecodeWithChar extends UDF{          public Text evaluate(Text param, Text charset) {         if (charset == null || charset.toString().length() == 0) {             charset = new Text("UTF-8");         }         String decode = null;         if (param == null) {             return param;         } else {             String str = param.toString();             try {                 decode = URLDecoder.decode(str, charset.toString());             } catch (UnsupportedEncodingException e) {                 decode = param.toString();             }         }         return new Text(decode);     }      }

將寫好的程式碼打成jar包.

建立臨時函式時:

       1. 將jar包放在linux某個目錄下,eg: /home/urldecode.jar

       2. 進入hive客戶端,如下操作:

       a) add jar /home/urldecode.jar;

       b). create temporary function urldecode as 'com.jobs.main.UrlDecodeWithChar';

臨時函式生成(只對當前session有效).

查詢結果:

hive > select 'Bom',urldecode('%E5%B9%BF%E5%B7%9E%E5%B8%82%E7%BB%BF%E7%9B%88%E6%B1%BD%E8%BD%A6%E6%9C%8D%E5%8A%A1%E6%9C%89%E9%99%90%E5%85%AC%E5%8F%B8') from ls limit 2;

Bom     廣州市綠盈汽車服務有限公司 Bom     廣州市綠盈汽車服務有限公司

檢視jar包

hive> list jar;

檢視自定義函式

hive> show functons; 

刪除自定義函式

hive> drop functon urldecode; 

生成永久函式

      1. 需要將jar包上傳到hdfs上面

       eg: hdfs dfs -put /home/urldecode.jar /usr/lib

      2. 建立永久函式

       create function urldecode as 'com.jobs.main.UrlDecodeWithChar' using jar 'hdfs:///usr/lib';

注意:執行這條語句建立永久函式,show functiuons 會加上預設的資料庫名在函式名前。(default.urldecode