大数据Hive篇--UDF函数

什么是UDF:

它是User defined Function的简写,意思是用户自定义方法

为什么要用UDF?

hive自带了一些函数,比如:max、min 等,但是自带的函数数量有限,所以hive提供给用户自定义函数的功能。
udf 函数可以直接应用于select 语句,对查询结构做格式化处理之后,然后再输出内容。

hive 编写udf函数的时候需要注意的地方:

1.自定义udf函数需要继承org.apache.hadoop.hive.ql.UDF
2.需要实现evaluate 函数,evaluate 函数支持重载。
3.udf 必须要有返回类型,可以返回null,但是返回类型不能为void;
4.udf 常用Text/LongWrite 等类型,不推荐使用java类型。

如何编写UDF

创建project 打jar包
<!-- https://mvnrepository.com/artifact/org.apache.hadoop/hadoop-common -->
    <dependency>
      <groupId>org.apache.hadoop</groupId>
      <artifactId>hadoop-common</artifactId>
      <version>2.6.0</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.hive/hive-exec -->
    <dependency>
      <groupId>org.apache.hive</groupId>
      <artifactId>hive-exec</artifactId>
      <version>1.1.0</version>
    </dependency>

需要hadoop的common包和hive的hive-exec

编写一个简单的函数

在输出的字段前加上’Hello’

package com.njbdqn;

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

public class MyFunc extends UDF {
    public Text evaluate(Text txt){
        return new Text("Hello,"+txt.toString());
    }
}

怎么使用函数

使用之前,先把包打包,我打的是瘦包,亲测可使用,如不行,可打胖包。
在这里插入图片描述

然后通过xftp传输到linux上
在这里插入图片描述

在linux启动了hadoop的前提下上传至hdfs端

将包上传hdfs:
hdfs dfs -mkdir -p /func
hdfs dfs -put /opt/jar/myfun-1.0-SNAPSHOT.jar /func

进入hive界面开始添加函数:

hive> add jar hdfs://192.168.56.100:9000/func/myfun-1.0-SNAPSHOT.jar;

创建新函数

create function mytest as "com.njbdqn.MyFunc";

选择表进行试验:

hive> select mytest(username) from userinfos limit 3;
OK
Hello,lhqye
Hello,gaqhq
Hello,thfqn
Time taken: 0.305 seconds, Fetched: 3 row(s)

此为原表内容:

hive> select username from userinfos limit 3;
OK
lhqye
gaqhq
thfqn
Time taken: 0.096 seconds, Fetched: 3 row(s)

可见此时编写的简单UDF函数已起作用。

  • 6
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值