0、为什么要自定义函数
hive 自带了一些函数,比如:max/min等,但是数量有限,自己可以通过自定义UDF来方便的扩展。
2)当Hive提供的内置函数无法满足你的业务处理需要时,此时就可以考虑使用用户自定义函数(UDF:user-defined function)。
3)根据用户自定义函数类别分为以下三种:
(1)UDF(User-Defined-Function)
一进一出
(2)UDAF(User-Defined Aggregation Function)
聚集函数,多进一出
类似于:count/max/min
(3)UDTF(User-Defined Table-Generating Functions)
一进多出
如lateral view explore()
编程步骤:
(1)继承org.apache.hadoop.hive.ql.exec.UDF
(2)需要实现evaluate函数;evaluate函数支持重载;
(3)在hive的命令行窗口创建函数
a)添加jar
add jar linux_jar_path
b)创建function
create [temporary] function [dbname.]function_name AS class_name;
(4)在hive的命令行窗口删除函数
Drop [temporary] function [if exists] [dbname.]function_name;
6)注意事项
(1)UDF必须要有返回类型,可以返回null,但是返回类型不能为void;
一、自定义UDF函数
1.创建一个Maven工程Hive
2.导入依赖
org.apache.hive hive-exec3.1.2
3.API
老接口:新建一个类,继承UDF
public class MyUDF extends UDF
需求:输入一个字符串,输出字符串长度
实现代码
public class MyUDF extends UDF {
public int evaluate(String input) {
if (input == null) {
return 0;
}
return input.length();
}
}
新接口继承GenericUDF继承方法
实现代码
package com.hive;
import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.exec.UDFArgumentLengthException;
import org.apache.hadoop.hive.ql.exec.UDFArgumentTypeException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDF;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;
public class MyNewUDF extends GenericUDF {
public ObjectInspector initialize(ObjectInspector[] arguments) throws UDFArgumentException {
if (arguments.length !=1){//判断输入参数个数,如果不等于一抛出异常参数个数错误
throw new UDFArgumentLengthException("Wrong arguments count,参数个数错误");
}//对参数类型做检查,如果不是String格式抛出异常,参数类型错误
if (!arguments[0].getCategory().equals(ObjectInspector.Category.PRIMITIVE)){
throw new UDFArgumentTypeException(0,"Wrong arguments type,参数类型错误");
}
//返回一个int类型
return PrimitiveObjectInspectorFactory.javaIntObjectInspector;
}
public Object evaluate(DeferredObject[] arguments) throws HiveException {
Object o = arguments[0].get();
if (o == null){
return 0;
}
return o.toString().length();
}
public String getDisplayString(String[] strings) {
return null;
}
}
4.将代码打包,上传到集群/opt/module/hive/lib/目录下
5.热添加jar包到CLASSPATH中让hive识别jar包、重启hive也可
add jar $HIVE_HOME/lib/hiveplugin-1.0-SNAPSHOT.jar;
6.将jar包关联到系统
create temporary function my_len as "com.hive.MyUDF";
create temporary function my_len as "com.hive.MyNewUDF";
7.测试
select name,my_len(name) from business;
select my_len("asasd","asasdd");
select my_len("asasd");
select my_len(split("ss","sd"));



