1. 程式人生 > 實用技巧 >建立 hive 使用者自定義函式UDF

建立 hive 使用者自定義函式UDF

目錄

1. 建立 Maven 工程

<dependencies>
    <!-- https://mvnrepository.com/artifact/org.apache.hive/hive-exec -->
    <dependency>
        <groupId>org.apache.hive</groupId>
        <artifactId>hive-exec</artifactId>
        <version>2.7.5</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.hadoop/hadoop-common -->
    <dependency>
        <groupId>org.apache.hadoop</groupId>
        <artifactId>hadoop-common</artifactId>
        <version>2.7.5</version>
    </dependency>
</dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.0</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>

2. 開發 Java 類整合 UDF

/**
 * @Author hwj
 * @Date 2020/8/5 20:15
 * @Desc: 模擬hive的upper方法:將字串的第一個字母轉大寫,其它不變
 **/
public class MyUDF extends UDF {
    public Text evaluate(final Text line){
        if(line.toString()!=null&& ! line.toString().equals("")){
            String str=line.toString().substring(0,1).toUpperCase()+line.toString().substring(1);
            return new Text(str);

        }
        return new Text("");
    }
}

3. 專案打包,並上傳到hive的lib目錄下


cd /export/servers/apache-hive-2.1.1-bin/lib

4. 新增jar包

重新命名 jar 包

mv hive_udf_upper-1.0-SNAPSHOT.jar Upper.jar

hive 客戶端新增 jar包

add jar /export/servers/apache-hive-2.1.1-bin/lib/Upper.jar;

5. 設定函式與我們的自定義函式關聯

create temporary function Upper as 'pers.hwj.udf.MyUDF';

6. 使用自定義函式

select Upper('hwj2020');


原始碼請地訪問github,對應標題下download