IT~技术交流群
添加微信号:liudd666haha
备注进群,会拉进交流群
互帮互助,IT之路不孤独!
本篇来源: https://liudongdong.top/archives/hiveshi-wu-hive-zhi-zi-ding-yi-udf-han-shu
[toc]
一、自定义函数概述
Hive 自带了一些函数
比如:max/min 等,但是数量有限,自己可以通过自定义 UDF 来方便的扩展。
当 Hive 提供的内置函数无法满足你的业务处理需要时,此时就可以考虑使用用户自定义函数(UDF:user-defined function)。
根据用户自定义函数类别分为以下三种:
UDF(User-Defined-Function) 一进一出
UDAF(User-Defined Aggregation Function) 聚集函数,多进一出 类似于:count/max/min
UDTF(User-Defined Table-Generating Functions) 一进多出 如 lateral view explode()
官方文档地址 https://cwiki.apache.org/confluence/display/Hive/HivePlugins
编程步骤:
继承 Hive 提供的类
org.apache.hadoop.hive.ql.udf.generic.GenericUDF
org.apache.hadoop.hive.ql.udf.generic.GenericUDTF;实现类中的抽象方法
在 hive 的命令行窗口创建函数 添加 jar
add jar linux_jar_path
创建 function
create [temporary] function [dbname.]function_name AS class_name;
在 hive 的命令行窗口删除函数
drop [temporary] function [if exists] [dbname.]function_name;
二、自定义 UDF 函数
需求:自定义一个 UDF 实现计算给定字符串的长度,例如:
hive(default)> select my_len("abcd");
创建一个 Maven 工程 Hive
导入依赖
<dependencies>
<dependency>
<groupId>org.apache.hive</groupId>
<artifactId>hive-exec</artifactId>
<version>3.1.2</version>
</dependency>
</dependencies>
创建一个类
package com.learn.hive;
import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
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.primitive.PrimitiveObjectInspectorFactory;
public class MyLength extends GenericUDF {
public ObjectInspector initialize(ObjectInspector[] objectInspectors) throws UDFArgumentException {
if (null == objectInspectors || objectInspectors.length != 1){
throw new UDFArgumentException("参数需为一个");
}
return PrimitiveObjectInspectorFactory.javaIntObjectInspector;
}
public Object evaluate(DeferredObject[] deferredObjects) throws HiveException {
Object obj = deferredObjects[0].get();
if (null == obj){
return 0;
}
return obj.toString().length();
}
public String getDisplayString(String[] strings) {
return "";
}
}打成 jar 包上传到服务器
/opt/module/hive/datas/demo_one-1.0-SNAPSHOT.jar
将 jar 包添加到 hive 的 classpath
hive (default)> add jar /opt/module/hive/datas/demo_one-1.0-SNAPSHOT.jar;
创建临时函数与开发好的 java class 关联
hive (default)> create temporary function my_len as "com.learn.hive.MyLength";
7)即可在 hql 中使用自定义的函数
hive (default)> select ename,my_len(ename) ename_len from emp;