本文共 2760 字,大约阅读时间需要 9 分钟。
虽然HIVE当中的函数功能很强大,但是有的时候我们需要自定义函数,今天我们介绍一个最简单的函数,UDF函数. 当
Hive 提供的内置函数无法满足你的业务处理需要时,此时就可以考虑使用用户自定义函数(UDF:user-defined function).
UDF:给参数计算出一个结果.
参考博客:https://www.cnblogs.com/jifengblog/p/9278972.html
直接进入正题,主要步骤:
回到顶部
UDF函数创建步骤 (1)新建Java Maven项目,添加依赖1
2 3 4 5 6 org.apache.hive hive-exec 0.13.1(2)继承UDF(org.apache.hadoop.hive.ql.exec.UDF)类,重写evaluate方法
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 package com.zmy.hive.udf;import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.exec.UDF;/**
注意:一定要用public修饰evaluate方法以及继承UDF的类,才能被hive调用,否则会报错(如下):
1
2 hive> select addtest(10,20); FAILED: SemanticException [Error 10014]: Line 1:7 Wrong arguments ‘20’: Unable to instantiate UDF implementation class ThreadProcess.AddTest: java.lang.IllegalAccessException: Class org.apache.hadoop.hive.ql.udf.generic.GenericUDFBridge can not access a member of class ThreadProcess.AddTest with modifiers “”(3)导出jar包
参考:https://www.cnblogs.com/zhangmingyang/protected/p/11450852.html
(4)部署jar包到hive所在的linux服务器
1
2 3 4 5 [mart_fro@BJLFRZ-Client-51-67 software]$ pwd /home/mart_fro/software [mart_fro@BJLFRZ-Client-51-67 software]$ ll total 8 -rw-r–r-- 1 mart_fro mart_fro 4668 Sep 17 09:44 udftest-1.0-SNAPSHOT.jar(5)在hive的命令行下添加jar包(注意:不需要加双引号),目的是添加jar包到hive的类classpath路径
1
2 3 hive> add jar /home/mart_fro/software/udftest-1.0-SNAPSHOT.jar; Added [/home/mart_fro/software/udftest-1.0-SNAPSHOT.jar] to class path Added resources: [/home/mart_fro/software/udftest-1.0-SNAPSHOT.jar] 如果没有这个步骤,后续会报错:1
2 3 hive> create temporary function addtest as ‘ThreadProcess.AddTest’; FAILED: Class ThreadProcess.AddTest not found FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.FunctionTask 需要注意的是:无论是临时函数还是永久函数,每次进入hive的时候都需要重新添加jar包,除非你将jar包位于hive/lib下.(6)注册函数和jar包进行关联,注册到当前的数据库当中(如果没有指定数据库,是默认的default库)
a. 临时函数,不会在mysql当中生成记录,每次都要重新注册.
1
2 3 4 5 6 create temporary function add as ‘com.zmy.hive.udf.AddUdf’; hive> desc function extended add; OK add(1,2) this is a extended info for add func!! Time taken: 0.018 seconds, Fetched: 2 row(s)b. 永久函数,会在mysql当中生成注册记录,不需要每次重新注册.
备注:这种方式非常重要,完全分布式时需要使用该方式,否则找不到函数类.
1
2 3 4 5 6 7 create function add as ‘com.zmy.hive.udf.AddUdf’; hive> desc function extended add; OK add(1,2) Synonyms: default.add this is a extended info for add func!! Time taken: 0.031 seconds, Fetched: 3 row(s)(7)调用自定义的UDF函数
1
2 3 hive> select add(1,2); 3 Time taken: 0.913 seconds, Fetched: 1 row(s)(8)注意查看mysql的注册信息 (略)
1
2 select * from bigg_hive.funcs ; select * from bigg_hive.func_ru ;