1. 程式人生 > >Impala使用者自定義函式(UDF)

Impala使用者自定義函式(UDF)

因業務需要用到MD5,但Impala沒有該函式,隨藉助UDF實現。以下是實現過程。

UDF實現要點:

  • 根據叢集中Hive的版本匯入對應版本的hive-exec.jar
  • 自定義UDF類要繼承介面UDF
  • 實現evaluate()方法

maven依賴:

        <dependency>
            <groupId>org.apache.hive</groupId>
            <artifactId>hive-exec</artifactId>
            <version>1.1.0</version>
        </dependency>

原始碼:

import org.apache.hadoop.hive.ql.exec.UDF;
import java.security.MessageDigest;

public class MD5 extends UDF{
    public static String evaluate(String value) {
        StringBuilder sb = new StringBuilder();
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            byte[] bytes = messageDigest.digest(value.getBytes());
            for (int i = 0; i < bytes.length; i++) {
                int tempInt = bytes[i] & 0xff;
                if (tempInt < 16) {
                    sb.append(0);
                }
                sb.append(Integer.toHexString(tempInt));
            }
        }
        catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return sb.toString();
    }


    public static void main(String[] args) {
        String hello = "123456789";
        System.out.println("MD5加密後的結果:" + evaluate(hello));
    }
}

匯出jar包:mvn package

上傳到Hdfs:hdfs dfs -copyFromLocal ./MyHiveUDF.jar /user/impala/user_function/,也可以使用Hue的File Browser上傳,更方便。

impala註冊:在hue的impala查詢介面(或者impala shell)中執行

create function md5(string) returns string location 'hdfs://nameservice/user/impala/user_function/MyHiveUDF.jar' symbol='com.business.bi.udf.MD5';

SQL說明:

md5(string) returns string 註冊的方法名為md5,輸入引數型別為string,返回值型別為string

location 'hdfs://nameservice/user/impala/user_function/MyHiveUDF.jar'  UDF方法的jar包位置

symbol='com.business.bi.udf.MD5'  自定義UDF的類名

測試:

select MD5('123456789')

輸出結果為 :25f9e794323b453885f5181f1b624d0b

上述過程執行完之後,在Hive中也可以使用該方法

參考:http://th7.cn/Program/java/201709/1257880.shtml