Hive-UDF
自定义函数

maven项目导包

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<hadoop.version>2.6.0</hadoop.version>
<hive.version>1.1.0</hive.version>
</properties>

<dependencies>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-common</artifactId>
<version>${hadoop.version}</version>
</dependency>
<dependency>
<groupId>org.apache.hive</groupId>
<artifactId>hive-exec</artifactId>
<version>${hive.version}</version>
</dependency>
</dependencies>

新建Hive-UDF类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// Hive UDF 需要实现 UDF
// UDF => import org.apache.hadoop.hive.ql.exec.UDF;

import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.hadoop.io.Text;

public class AvgCost extends UDF {
// UDF 必须有个 evaluate 方法,也可以有多个实现重载
// evaluate 返回的数据类型必须是 java 基础类型或Hadoop Writerbel 数据类型
// 建议Hadoop Writerbel 数据类型, 因为底层是MR
// 返回的数据类型必须是 Text
public Text evaluate (Text input){
Text output = new Text();
if (!input.toString().isEmpty()){
output.set("None");
}
String[] salary = input.toString().split("-");
if (salary.length == 1){
output.set(salary[0] + " - " + salary[0]);
}
if (salary.length == 2){
int salary1 = Integer.parseInt(salary[0]);
int salary2 = Integer.parseInt(salary[1]);
Double avgSalary = (salary1+salary2)*1.0/2;
if (salary1 > salary2){
output.set(salary1 + " - " + salary2 + " - " + avgSalary);
}else{
output.set(salary2 + " - " + salary1 + " - " + avgSalary);
}
}

return output;
}

打jar包上传到服务器

添加jar包到hive中,并导入函数

1
2
3
4
5
6
7
8
9
10
11
12
13
1. 导入jar包
hive> add jar jar包路径
2. 导入函数
-语法: crate [temporary] function [dbName]functionName as 'packageAddress'
-a 导入成临时函数
hive> create temporary function avgcost as 'com.org.udf.AvgCost.AvgCost';
-b 导入成永久函数
hive> create function dbName.avgcost as 'com.org.udf.AvgCost.AvgCost';

// 导入成永久函数可以决定作用域[dbName] 是哪个数据库,函数就只能在哪个数据库中调用,临时函数无法指定

3.使用函数 => 直接用函数名就可以调用
hive> select avgcost(salary) as salary from rawData;