Hive的UDF(用户自定义函数)开发

  当 Hive 提供的内置函数无法满足你的业务处理需要时,此时就可以考虑使用用户自定义函数(UDF:user-defined function)。

测试各种内置函数的快捷方法:

创建一个 dual 表

create table dual(id string);

load 一个文件(只有一行内容:内容为一个空格)到 dual 表

新建 JAVA maven 项目

添加依赖

<dependencies>
        <dependency>
            <groupId>org.apache.hive</groupId>
            <artifactId>hive-exec</artifactId>
            <version>1.2.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-common</artifactId>
            <version>2.7.4</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>2.2</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <filters>
                                <filter>
                                    <artifact>*:*</artifact>
                                    <excludes>
                                        <exclude>META-INF/*.SF</exclude>
                                        <exclude>META-INF/*.DSA</exclude>
                                        <exclude>META-INF/*.RSA</exclude>
                                    </excludes>
                                </filter>
                            </filters>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

编写一个 java 类,继承 UDF,并重载 evaluate 方法

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

/**
 * hive的自定义函数
 */
public class ItcastFunc extends UDF{
    //重载
    public String evaluate(String input){
        return input.toLowerCase();//将大写字母转换成小写
    }

    public int evaluate(int a,int b){
        return a+b;//计算两个数之和
    }
}

打成 jar 包上传到服务器

将 jar 包添加到 hive 的 classpath

  

hive>add JAR /root/hivedata/udf.jar;

创建临时函数与开发好的 java class 关联

create temporary function udffunc as 'hive.udf.UDFFunc';//temporary表示为临时方法,当会话结束后失效;udffunc为hive中定义的函数名,‘hive.udf.UDFFunc’为自定义方法的全类路径

在 hive中使用自定义的函数 

select udffunc("ABC") from dual;//输出abc
select udffunc(2,3) from dual;//输出5
原文地址:https://www.cnblogs.com/jifengblog/p/9278972.html