版权声明:转载,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接: https://blog.csdn.net/weixin_43326165/article/details/100747147

实现

  1. 定义一个类,继承UDF,然后写evaluate方法

    查看UDF类,会发现并没有这个方法(版本1.2.1))),所以说重写有点牵强~

    源码中这样写到:

    Implement one or more methods named {@code evaluate} which will be called by Hive 
    (the exact way in which Hive resolves the method to call can be configured by setting a custom
    实现一个或者更多名为evaluate的方法,这个方法会被hive调用(这是hive去调用自定义方法最好的方式)
    

{@code evaluate} should never be a void method. However it can return {@code null} i * needed.
evaluate不能定义为void返回,但是可以返回NULL

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
public class UDFDemo extends UDF {
    /** * 参数是你方法输入的参数类型。 * 有一点是如果传入的参数是bigint,要用Text(Hadoop io包的) * 返回类型是自定义的 * 所有的参数以及返回类型可以是Java的也可以是hadoop io的 */
    public String evaluate(String str,String b){
        //示例,就不验证了,意思一下
        return a+"_"+b;
    }
}

 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 打成jar包,放到服务器上

  • 使用自定义函数

    1. 第一种(本session有效)
    # 导入jar包
    hive (zzy)> add jar /home/zzy/wc.jar;
    Added [/home/zzy/wc.jar] to class path
    Added resources: [/home/zzy/wc.jar]
    # 创建为临时的函数,函数名mycon(自定义的)
    hive (zzy)> create temporary function mycon as 'cn.zzy.hive.API.UDFDemo';
    OK
    Time taken: 0.019 seconds
    # 查看是否成功
    hive (zzy)> show functions like '*UDF*';
    OK
    UDFDemo
    Time taken: 0.005 seconds, Fetched: 1 row(s)
    hive (zzy)> select mycon('o','o');
    OK
    o_o
    
      
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    1. 第二种(也是在本session有效,临时函数)

      1. vi ./hive-init
        add jar /home/zzy/wc.jar;
        create temporary function mycon as 'cn.zzy.hive.API.UDFDemo';
        

    #启动hive的时候带上初始化文件:这个文件位置可以任意,启动的时候填上路径就好了
    hive -i ./hive-init

    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
  • 第三种(永久函数 推荐

    1. 将编写的udf的jar包上传到服务器上

      hive>create function mycon as 'cn.zzy.hive.API.UDFDemo' using jar hdfs://hadoop001:9000/wc.jar;
      
          
      • 1

      注意点:这样的函数是永久的(如果HDFS上文件不被删除),但是默认是default.mycon。即默认是在default库中,在别的库中调用写全称。

  • 第四种(永久函数 推荐 )

    1. 在hive安装目录下新建一个auxlib文件假

    2. 将jar包放进去

      create temporary function mycon as 'cn.zzy.hive.API.UDFDemo';
      
          
      • 1

      还是在default库中,全名default.mycon

  • 其实还有很多。就不介绍了,最常用的说了。

                                    </div>
                <link href="https://csdnimg.cn/release/phoenix/mdeditor/markdown_views-e44c3c0e64.css" rel="stylesheet">
                    </div>