Hive中3种自定义函数及其区别(在于输入和输出的行数)
函数 | 区别 |
---|---|
UDF | 一行输入,一行输出 |
UDGF | 多行输入,一行输出 |
UDTF | 单行输入,多行输出(table) |
下面只介绍一个 UDF 实例:
🌰函数名 UDF_zr,查询学生(输入字段:student_xxx.Birth)出生天数。流程如下:
以此表student_zr为例:
Name | Sex | Birth | Dept | Uid |
---|---|---|---|---|
Liuyi | F | 2002/11/26 | CS | 180301 |
Chener | F | 2001/6/11 | CS | 180302 |
Zhangsan | M | 2002/9/21 | CS | 180303 |
Lisi | F | 2001/1/26 | SE | 180201 |
(1)Eclipse 中新建一个 Java 项目,自定义一个 Java 类,添加 hive 安装目录下 lib 文件夹所有 jar 包,Hadoop 中 share 下 hadoop-common 包,其它 jar 包请依据程序需要添加;
(2)自定义类需要继承 import org.apache.hadoop.hive.ql.exec.UDF 类,UDF 是必须导入import,其它类依据程序使用导入。然后重写 evaluate 方法;
import java.util.Date;
import java.util.Scanner;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import org.apache.hadoop.hive.ql.exec.UDF;
@SuppressWarnings("deprecation")
public class UDFDemo_zr extends UDF{
public String evaluate(String sec) throws ParseException{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
Date birthday = sdf.parse(sec);//调用方法prase,将字符串转换成日期对象
Date today = new Date();//获取今天的日期对象
long secone =today.getTime() - birthday.getTime();
String str=Long.toString(secone/1000/60/60/24);
return str;
}
@SuppressWarnings("resource")
public static void main(String[] args) throws ParseException {
System.out.println(new UDFDemo_zr().evaluate(new Scanner(System.in).next()));
}
}
(3)将类打包成 jar 包,Export 导出 jar 包,选择 JAR FILE,选择要导出的项目、存放路径导出 jar 包。
(4)进入 Hive shell,add jar 命令导入 jar 包到 Hive 环境变量里。
hive> add jar /home/zr/UDFDemo.jar;
(5)要使用函数还要在 Hive 环境中定义临时函数,create temporary 函数名 as‘类名’命令基于包中的类创建临时函数。
hive> create temporary function UDF_zr as 'UDFDemo_zr';
OK
Time taken: 0.075 seconds
hive> show functions like 'U*';
OK
ucase
udf_zr
udftoboolean
udftobyte
udftodouble
udftofloat
udftointeger
udftolong
udftoshort
udftostring
unbase64
unhex
unix_timestamp
upper
uuid
Time taken: 0.526 seconds, Fetched: 15 row(s)
(6)HQL 中使用 UDF 函数。
hive> select * from student_zr;
OK
Liuyi F 2002/11/26 180301 CS
Chener F 2001/6/11 180302 CS
Zhangsan M 2002/9/21 180303 CS
Lisi F 2001/1/26 180201 SE
Time taken: 8.409 seconds, Fetched: 4 row(s)
hive> select UDF_zr(Birth) from student_zr;
OK
6763
7296
6829
7432
Time taken: 5.393 seconds, Fetched: 4 row(s)
(7)使用完毕,drop temporary function 可以删除临时函数。
hive> drop temporary function UDF_zr;
OK
Time taken: 0.415 seconds
hive> show functions like 'U*';
OK
ucase
udftoboolean
udftobyte
udftodouble
udftofloat
udftointeger
udftolong
udftoshort
udftostring
unbase64
unhex
unix_timestamp
upper
uuid
Time taken: 0.202 seconds, Fetched: 14 row(s)
❌出现的问题——未出现预想的结果:
hive> select UDF_zr(Birth) from student_zr;
OK
2002/11/26
2001/6/11
2002/9/21
2001/1/26
Time taken: 6.684 seconds, Fetched: 4 row(s)
⭕原因——未将代码写入evaluate中: