Hive 自定义函数-UDF

9 篇文章 0 订阅
8 篇文章 0 订阅

为什么要自定义函数

hive的内置函数无法满足实际开发环境的所有情况,这个时候需要我们根据业务自定义函数来解决问题。
hive提供了很多模块的自定义功能,如:serde、自定义函数、输入输出格式化等

常见的自定义函数

UDF:User Define Function.一对一的输入输出,非常使用。
UDAF:User Define Agregation Function.用户的自定义聚合函数。多对一的输入输出 
UDTF:User Define Table‐Generate Function.用户自定的表生成函数。

如何编写UDF

1. 继承UDF类,自定义evaluate(),允许重载。 
2. 继承GenericUDF,重写initlizer、getdisplay、evaluate方法

案例

自定义函数,根据出生日期求年龄
导入依赖
<dependency>
	<groupId>org.apache.hive</groupId>
	<artifactId>hive-exec</artifactId>
	<version>2.1.1</version>
</dependency>
编码实现
// 继承UDF类
public class MyUDF extends UDF {
// 实现evaluate方法
    public int evaluate(String birth) {
        String[] info = birth.split("-");
        int birth_year = Integer.parseInt(info[0]);
        int birth_month = Integer.parseInt(info[1]);
        int birth_day = Integer.parseInt(info[2]);

        Calendar now = Calendar.getInstance();
        int now_year = now.get(Calendar.YEAR);
        int now_month = now.get(Calendar.MONTH);
        int now_day = now.get(Calendar.DAY_OF_MONTH);

        int age = now_year - birth_year;
        if (birth_month < now_month) {
            age -= 1;
        } else if (birth_day < now_day) {
            age -= 1;
        }
        return age;
    }
}
将项目打成jar包
上传到HDFS上
hdfs dfs -put birth_age.jar /jar/birth_age.jar
在Hive中添加jar并创建函数
CREATE FUNCTION `hive`.`birth_age` AS 'com.qf.udf.MyUDF' USING JAR 'hdfs://192.168.10.101//jar/birth_age.jar';
案例演示
hive> select birth_age(1997-01-01);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值