UDF
全称:user define function
作用: in:out=1:1,只能输入一条记录,同时返回一条处理结果。
1.实现步骤
- 创建一个java类
- 继承UDF类
- 约定俗称的重写evaluate方法
- 打成jar包上传到hdfs中
- 在hive中 使用add jar 命令将jar包加入到classpath中
- 创建函数 create temporary function name ‘主类’;
- 使用函数
2.示例
完成一个将字符串加密成md5的函数
package com.antg;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.hadoop.hive.ql.exec.UDF;
/**
* @author Antg
* @date 2021/10/21 1:18
*/
public class Hw01 extends UDF {
public String evaluate(String input){
return DigestUtils.md5Hex(input);
}
}
- 打包
- mvn clean package
- 上传
- rz -bye
- hdfs dfs -put Hw.jar /user/antg/hive
- 添加到classpath中(hive环境中)
- add jar Hw.jar
- 创建函数
- create temporary function md5 “com.antg.Hw01”;
- 使用函数
- select md5(username) from student;
- ![image.png](https://img-blog.csdnimg.cn/img_convert/a3431b553329cfc382e4cceb307b9529.png#clientId=u5016a7fd-d5b1-4&from=paste&height=215&id=uc6029b20&margin=[object Object]&name=image.png&originHeight=429&originWidth=891&originalType=binary&ratio=1&size=57815&status=done&style=none&taskId=uc0ca5a96-96ac-489b-9121-46283240317&width=445.5)
UDAF
全称: user define aggregation function
作用: 自定义聚合函数,类似count的多输入,单输出函数
1.实现步骤
- 创建java类
- 继承UDAF
- 创建静态内部类Evaluator并实现接口UDAFEvaluator
- 实现方法init 相当于setup方法 map和reduce均会执行该函数
- 重写约定方法
- iterate 相当于map方法,返回值为boolean类型,当为true则程序继续执行,当为false则程序退出
- terminatePartial 类似于combiner,在map范围内做部分聚合,将结果传给merge函数中的形参mapOutput,如果需要聚合,则对iterator返回的结果处理,否则直接返回iterator的结果即可
- merge 相当于reduce方法 用于逐个迭代处理map当中每个不同key对应的 terminatePartial的结果
- terminate 处理merge计算完成后的结果
- 打包上传
- 添加jar包到类路径
- 创建函数
- 使用函数
2.示例
package com.antg;
import org.apache.hadoop.hive.ql.exec.UDAF;
import org.apache.hadoop.hive.ql.exec.UDAFEvaluator;
import org.apache.hadoop.io.IntWritable;
/**
* @author Antg
* @date 2021/10/21 1:32
*/
public class Hw02 extends UDAF {
public static class Evaluator implements UDAFEvaluator {
private int result;
@Override
public void init() {
}
//map阶段 这个就相当于map方法
//返回值是boolean,ture就是继续循环,false就是结束这个map任务
public boolean iterate(int value) {
result = Math.max(value,result);
return true;
}
//局部的合并,相当于combiner
//合并完后将结果传送到reduce节点
public int terminatePartial() {
return result;
}
//处理map来的节点
public boolean merge(int value) {
return iterate(value);
}
//合并reduce节点的数据并做最后的输出
public int terminate() {
return result;
}
}
}
其他步骤和UDF一样
UDTF
全称 user define table-generating function
解决一行输入,多行输出的问题 即行转列
往往被lateral view explode+udf等替代实现,比直接用udtf会更简单、直接、更灵活一些