Hive自定义函数

Hive自定义函数

关于HIVE实现自定义函数,步骤主要可分为:

  • 继承org.apache.hadoop.hive.ql.exec.UDF
  • 重写evaluate()方法
  • 打包jar
  • 添加jar包
  • 使用自定义函数

下面是具体实现,包括自定义临时函数和自定义永久函数。

编写自定义函数

1
2
3
4
5
6
7
8
public class AddPrefix extends UDF {
/**
* 这里我们实现将任一输入添加自定义前缀信息
*/
public String evaluate(String str) {
return "HIVE UDF Prefix:"+ str;
}
}

自定义临时函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
--添加jar包
hive> add jar /usr/henrrywan/addPrefix.jar;

--创建自定义临时函数
hive> create temporary function add_prefix as 'com.test.AddPrefix';

--使用自定义临时函数
hive> select add_prefix('aa');
HIVE UDF Prefix:aa
hive> select add_prefix(1);
HIVE UDF Prefix:1

--这里我们切换数据库依然可以正常使用。为了便于观察,我们打开数据库显示。
hive> set hive.cli.print.current.db=true;
hive (test)> select add_prefix('aa');
HIVE UDF Prefix:aa
hive (test)> use tmp;
hive (tmp)> select add_prefix('aa');
HIVE UDF Prefix:aa

--销毁自定义临时函数
hive (test)> drop temporary function add_prefix;
--需要注意的是,一旦退出HIVE客户端,自定义临时函数即被销毁。

自定义永久函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
## 上传jar包到HDFS
[root@nd2 henrrywan]# hadoop fs -put addPrefix.jar /henrrywan/test/
[root@nd2 henrrywan]# hadoop fs -ls /henrrywan/test
Found 1 items
-rw-r--r-- 3 root supergroup 699 2019-05-22 14:03 /henrrywan/test/addPrefix.jar

## 创建永久函数
create function add_prefix
as 'com.test.AddPrefix'
using jar 'hdfs:///henrrywan/test/addPrefix.jar'

## 与自定义临时函数不同,使用永久函数只能在当前数据库。这里我们放在test库,如果在其它库执行,会报错
hive (test)> select add_prefix('aa');
HIVE UDF Prefix:aa
hive> use tmp;
hive (tmp)> select add_prefix('aa');
FAILED: SemanticException [Error 10011]: Invalid function add_prefix

## 销毁自定义永久函数
hive (test)> drop function add_prefix;
打赏
  • 版权声明: 本博客所有文章除特别声明外,著作权归作者所有。转载请注明出处!
  • Copyrights © 2015-2023 henrrywan

请我喝杯咖啡吧~

支付宝
微信