天天看點

【二十】hive自定義函數開發

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.sid.hive.udf</groupId>
    <artifactId>hiveudf</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <hadoop.version>2.9.0</hadoop.version>
        <hive.version>2.3.3</hive.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-common</artifactId>
            <version>${hadoop.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.hive</groupId>
            <artifactId>hive-exec</artifactId>
            <version>${hive.version}</version>
        </dependency>

    </dependencies>


</project>
           
udftest.java      
package udf;

import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.hadoop.io.Text;
/**
 * hive 自定義函數
 *
 * 1.繼承UDF類
 * 2.重寫evaluate方法
 * */
public final class udftest extends UDF {
    /**
     * 這裡接收參數的類型必須是hadoop能支援的輸入輸出類型
     * */
    public Text evaluate(final Text s) {
        if (s == null) {
            return null;
        }
        return new Text(s.toString().toLowerCase());
    }
}
           

打包

【二十】hive自定義函數開發

把生成的jar包上傳到hive所在的伺服器

把jar包添加到hive中

cd /app/hive/bin

hive

【二十】hive自定義函數開發
add jar /app/hive/testData/hiveudf-1.0-SNAPSHOT.jar;
           
【二十】hive自定義函數開發

檢視導入的jar包

list jar;
           
【二十】hive自定義函數開發

建立臨時函數。隻在目前會話有效。

create temporary function test_udf_lower as 'udf.udftest';
           

使用這個自定義函數

select id,name,manager,test_udf_lower(manager) from dept;
           

結果

【二十】hive自定義函數開發

建立永久的自定義函數

将jar包放到hdfs上,不可以放到OS上。

建立的是在sid庫下面的自定義函數。

create function sid.test_udf_lower
  as 'udf.udftest' 
  using jar 'hdfs:///tmp//hiveudf-1.0-SNAPSHOT.jar';
use sid;
select id,name,manager,test_udf_lower(manager) from dept;
           

繼續閱讀