天天看點

Hive中的使用者自定義函數UDF

Hive 内置函數

Date Functions
Conditional Functions
Misc. Functions
           

Hive自定義函數

  • UDF

    (User-Defined-Function) 一進一出
  • UDAF

    (User- Defined Aggregation Funcation) 聚集函數,多進一出。Count/max/min
  • UDTF

    (User-Defined Table-Generating Functions) 一進多出,如

    explode()

    使用方式 :在HIVE會話中add 自定義函數的jar檔案,然後建立function繼而使用函數

UDF 開發

  1. UDF函數可以直接應用于select語句,對查詢結構

    做格式化處理

    後,再輸出内容
  2. 編寫UDF函要注意以下幾點:

    a. 自定義UDF需要繼承

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

    b. 需要實作evaluate函數,evaluate函數支援重載
  3. 步驟

    a. 把程式打包放到目标機器上去;

    b. 進入hive用戶端,添加jar包:hive> 

    add jar /run/jar/udf_test.jar;

    c. 建立臨時函數:hive> 

    CREATE TEMPORARY FUNCTION add_example AS 'hive.udf.Add';

    d. 銷毀臨時函數:hive> 

    DROP TEMPORARY FUNCTION add_example;

    e. 查詢HQL語句:
SELECT add_example(8, 9) FROM scores;
SELECT add_example(scores.math, scores.art) FROM scores;
SELECT add_example(6, 7, 8, 6.8) FROM scores;
           

Hive的UDF開發隻需要重構UDF類的evaluate函數即可

package com.hrj.hive.udf;
import org.apache.hadoop.hive.ql.exec.UDF;
public class helloUDF extends UDF {
    public String evaluate(String str) {
        try {
            return "HelloWorld " + str;
        } catch (Exception e) {
            return null;
        }
    }
} 
           

Hive 自定義函數調用

将該java檔案編譯成helloudf.jar
hive> add jar helloudf.jar;
hive> create temporary function helloworld as 'com.hrj.hive.udf.helloUDF';
hive> select helloworld(t.col1) from t limit 10;
hive> drop temporary function helloworld;
           

1.helloworld為臨時的函數,是以每次進入hive都需要add jar以及create temporary操作

2.UDF隻能實作一進一出的操作,如果需要實作多進一出,則需要實作UDAF

Hive中的使用者自定義函數UDF

Hive複合資料類型

Hive中的使用者自定義函數UDF

Hive操作複合類型

繼續閱讀