hive的UDF编写例子

1.Hive 的udf使用需用需要的依赖

<?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>xxxx</groupId>
    <artifactId>xxxx</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
        <scala.binary.version>2.11</scala.binary.version>
        <maven.compiler.source>${java.version}</maven.compiler.source>
        <maven.compiler.target>${java.version}</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-common</artifactId>
            <version>2.7.7</version>
        </dependency>
        <dependency>
            <groupId>org.apache.hive</groupId>
            <artifactId>hive-exec</artifactId>
            <version>1.2.1</version>
        </dependency>
    </dependencies>
</project>

2.Hive的udf是干什么的?

如:你在hadoop的hive中执行了一个 hql 语句 select itcastfun('ABC') from dual;

会报编译错误,因为hive中没有 itcastfun函数,这个函数是我们自定义的

3.如何使用udf?

1)使用idea编辑器编写java代码

复制代码
 1 package agg.hive.udf;
 2 ​
 3 import org.apache.hadoop.hive.ql.exec.UDF;
 4 ​
 5 public class ItcastFunc extends UDF{
 6     /*继承了 UDF 需要重载 evaluate 这个函数*/
 7     public String evaluate(String input){
 8         if(input==null){
 9             return null;
10         }
11         return input.toLowerCase();
12     }
13 ​
14     public int evaluate(int a , int b){
15         return a + b;
16     }
17 }
复制代码

2)编写完成之后,通过maven的打包工具 package打成jar包的形式,完事把jar包复制出来,编辑器暂时就没用了

3)把jar包上传到 hive 的服务器上,此时就不能使用hive的远程连接上传了,必须用hive的服务器端上传(因为udf函数操作已经涉及到了hive的核心内部的改变了)

(上传jar包:直接拖动jar到hadoop服务器,我的hive是在主节点上;

我这里上传了两个jar包,因为我打包的时候生成了两个,我也不知道是哪个,所以直接全部上传进行试验)

4)jar上传到hive的服务器之后,直接使用hive的如下命令,将jar包添加到hive的classpath:

 1 hive>add jar /home/badou/HadoopTest-1.0-SNAPSHOT.jar; 

5)jar添加hive完成之后,需要创建一个function 函数

下面的语句中 temporary 关键字表示创建的临时函数,即结束了hive的进程再重新进入之后该函数就消失了,这样一来也证明了该函数谁创建谁负责,谁使用谁维护的原则,大家互不影响

路径为java类的路径(在java类名上双击选中->右键-> Copy Reference即可得到路径)

 1 hive> create temporary function itcastfun as 'agg.hive.udf.ItcastFunc';  

执行完成之后会直接提示 OK

6)此时我们就可以直接使用我们自定义的函数了,函数名如上定义的 itcastfun ;

因为我们的自定义函数中有两个重载的方法,这里我们写两个 sql 语句进行测试:

1 select itcastfun('ABC') from dual;
2 select itcastfun(2,3) from dual;
3 或者
4 select itcastfun('ABC') ;
5 select itcastfun(2,3) ;

返回结果如下:

转载:https://www.cnblogs.com/singleYao/p/13764780.html

原文地址:https://www.cnblogs.com/to-here/p/15430305.html