阿里云-云小站(无限量代金券发放中)
【腾讯云】云服务器、云数据库、COS、CDN、短信等热卖云产品特惠抢购

Hive自定义函数UDF、UDTF、UDAF入门

157次阅读
没有评论

共计 7678 个字符,预计需要花费 20 分钟才能阅读完成。

详细讲解 Hive 自定义函数 UDF、UDTF、UDAF 基础知识,带你快速入门,首先在 Hive 中新建表”apache_log”

CREATE TABLE apachelog (
  host STRING,
  identity STRING,
  user STRING,
  time STRING,
  request STRING,
  status STRING,
  size STRING,
  referer STRING,
  agent STRING)
ROW FORMAT SERDE ‘org.apache.Hadoop.hive.serde2.RegexSerDe’
WITH SERDEPROPERTIES (
  “input.regex” = “([^]*) ([^]*) ([^]*) (-|\\[[^\\]*\\]]) ([^ \”]*|\”[^\”]*\”) (-|[0-9]*) (-|[0-9]*) (?: ([^ \”]*|\”.*\”) ([^ \”]*|\”.*\”))?”
)
STORED AS TEXTFILE;

这个是官方给出的实例,但是是错的。

Hive 自定义函数 UDF、UDTF、UDAF 入门

不过,已经有人给做出了修改。

Hive 自定义函数 UDF、UDTF、UDAF 入门

Hive 自定义函数 UDF、UDTF、UDAF 入门

接下来结合一些样例数据

27.19.74.143 – – [29/April/2016:17:38:20 +0800] “GET /static/image/common/faq.gif HTTP/1.1” 200 1127
110.52.250.126 – – [29/April/2016:17:38:20 +0800] “GET /data/cache/style_1_widthauto.css?y7a HTTP/1.1” 200 1292
27.19.74.143 – – [29/April/2016:17:38:20 +0800] “GET /static/image/common/hot_1.gif HTTP/1.1” 200 680
27.19.74.143 – – [29/April/2016:17:38:20 +0800] “GET /static/image/common/hot_2.gif HTTP/1.1” 200 682
27.19.74.143 – – [29/April/2016:17:38:20 +0800] “GET /static/image/filetype/common.gif HTTP/1.1” 200 90
110.52.250.126 – – [29/April/2016:17:38:20 +0800] “GET /source/plugin/wsh_wx/img/wsh_zk.css HTTP/1.1” 200 1482
110.52.250.126 – – [29/April/2016:17:38:20 +0800] “GET /data/cache/style_1_forum_index.css?y7a HTTP/1.1” 200 2331
110.52.250.126 – – [29/April/2016:17:38:20 +0800] “GET /source/plugin/wsh_wx/img/wx_jqr.gif HTTP/1.1” 200 1770
27.19.74.143 – – [29/April/2016:17:38:20 +0800] “GET /static/image/common/recommend_1.gif HTTP/1.1” 200 1028
110.52.250.126 – – [29/April/2016:17:38:20 +0800] “GET /static/image/common/logo.png HTTP/1.1” 200 4542
……

这个是 apache 服务器的日志信息,一共七个字段,分别表示:”host”、”identity”、”user”、”time”、”request”、”status”、”size”,在 hive 官网上是有九个字段的,剩下两个为:”referer”、”agent”。

—————————————— 分割线 ——————————————

样例数据 相关资料可从以下信息得到下载:

点击这个 http://www.linuxidc.com/Linux/2013-12/93755.htm 链接 关注 Linux 公社官方微信,关注后回复数字151443。即可得到网友的分享密码。

如果取消关注 Linux 公社公众号,即使再次关注,也将无法提供本服务!

链接:https://pan.baidu.com/s/1dvBorZch0WFPMPO2xqZTLQ 密码:获得见上面的方法,地址失效请在下面留言。

—————————————— 分割线 ——————————————

我们根据这些数据,从一些小需求中来体会一下这三种函数。

UDF(user-defined functions)
“小”需求:
 提取”time”,转换成”yyyy-MM-dd HH:mm:ss”格式。

要点:
1. 继承自“org.apache.hadoop.hive.ql.exec.UDF”;
2. 实现”evaluate()”方法。

*JAVA 代码 *
package com.hadoop.hivetest.udf;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

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

public class MyDateParser extends UDF{
    public String evaluate(String s){
        SimpleDateFormat formator = new SimpleDateFormat(“dd/MMMMM/yyyy:HH:mm:ss Z”,Locale.ENGLISH);
        if(s.indexOf(“[“)>-1){
            s = s.replace(“[“, “”);
        }
        if(s.indexOf(“]”)>-1){
            s = s.replace(“]”, “”);
        }

        try {
            // 将输入的 string 转换成 date 数据类型
            Date date = formator.parse(s);
            SimpleDateFormat rformator = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);
            return rformator.format(date);
        } catch (ParseException e) {
            e.printStackTrace();
            return “”;
        }
    }
}

小插曲
导出为 jar 包,发送到 Linux 上。这次我们可以使用 editplus 编辑器来上传:

– 打开 editplus,选择”File—FTP—FTP Setting”–
Hive 自定义函数 UDF、UDTF、UDAF 入门

– 选择添加 –
Hive 自定义函数 UDF、UDTF、UDAF 入门
并且在相应的字段上填上值,对于”Subdirectory”这一项要填写的是你希望上传到 Linux 上的哪个目录。

– 点击”Advanced Options”–
Hive 自定义函数 UDF、UDTF、UDAF 入门
之后便可以一路 OK 回去。

– 选择 FTP Upload –
Hive 自定义函数 UDF、UDTF、UDAF 入门
在这里找到要上传的文件,选择要上传到哪一个账户上,并选择”Upload”即可。

然后我们就可以在”Subdirectory”中写到的目录下去找我们的文件了。
Hive 自定义函数 UDF、UDTF、UDAF 入门
– 小插曲结束 –

之后我们使用 beeline 客户端来连接 hive
Hive 自定义函数 UDF、UDTF、UDAF 入门
然后我们可以新建一个数据库,并使用之前的建表语句来创建”apache_log”,并导入数据(默认大家都会了 ^.^)。
Hive 自定义函数 UDF、UDTF、UDAF 入门

Step 1: add jar“jar-path”
Hive 自定义函数 UDF、UDTF、UDAF 入门

Step 2: create function timeparse as‘包名 + 类名’
Hive 自定义函数 UDF、UDTF、UDAF 入门

Step 3: 使用该函数
Hive 自定义函数 UDF、UDTF、UDAF 入门
对比之前我们导入的数据
Hive 自定义函数 UDF、UDTF、UDAF 入门

UDTF(user-defined table-generating functions)
“小”需求:
针对”request”字段,将其拆分,获取到用户的请求连接。
第一部分表示请求的方式,第二部分为用户请求的连接,第三部分为协及版本号。

要点:
1. 继承自”org.apache.hadoop.hive.ql.udf.generic.GenericUDTF”;
2. 实现 initialize()、process()、close()三个方法。

*JAVA 代码
package com.hadoop.hivetest.udf;

import java.util.ArrayList;

import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDTF;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;

public class MyRequestParser extends GenericUDTF {

    @Override
    public StructObjectInspector initialize(ObjectInspector[] arg0) throws UDFArgumentException {
        if(arg0.length != 1){
            throw new UDFArgumentException(“ 参数不正确。”);
        }
        ArrayList<String> fieldNames = new ArrayList<String>();
        ArrayList<ObjectInspector> fieldOIs = new ArrayList<ObjectInspector>();

        // 添加返回字段设置
        fieldNames.add(“rcol1”);
        fieldOIs.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector);

        fieldNames.add(“rcol2”);
        fieldOIs.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector);

        fieldNames.add(“rcol3”);
        fieldOIs.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector);

        // 将返回字段设置到该 UDTF 的返回值类型中
        return ObjectInspectorFactory.getStandardStructObjectInspector(fieldNames, fieldOIs); 
    }
    @Override
    public void close() throws HiveException {

    }

    // 处理函数的输入并且输出结果的过程
    @Override
    public void process(Object[] args) throws HiveException {
        String input = args[0].toString();

        input = input.replace(“\””, “”);

        String[] result = input.split(” “);
        // 如果解析错误或失败,则返回三个字段内容都是 ”–“
        if(result.length != 3){
            result[0] = “–“;
            result[1] = “–“;
            result[2] = “–“;
        }
        forward(result);
    }
}

依照上面的步骤,导出 jar 包,上传到 Linux 服务器上。在此不再赘述,其实是攒着另一种上传文件的方式,下次教给大家。

Step 1: add jar“jar-path”

Step 2: create function requestparse as‘包名 + 类名’
Hive 自定义函数 UDF、UDTF、UDAF 入门

Step 3: 使用该函数
Hive 自定义函数 UDF、UDTF、UDAF 入门
对比我们之前导入的数据
Hive 自定义函数 UDF、UDTF、UDAF 入门

UDAF(user-defined aggregation functions)
“小”需求:
求出最大的流量值

要点:
1. 继承自”org.apache.hadoop.hive.ql.exec.UDAF”;
2. 自定义的内部类要实现接口”org.apache.hadoop.hive.ql.exec.UDAFEvaluator”;
3. 要实现 iterate()、terminatePartial()、merge()、terminate()四个方法。

*JAVA 代码
package com.hadoop.hivetest.udf;

import org.apache.hadoop.hive.ql.exec.UDAF;
import org.apache.hadoop.hive.ql.exec.UDAFEvaluator;
import org.apache.hadoop.io.IntWritable;

@SuppressWarnings(“deprecation”)
public class MaxFlowUDAF extends UDAF {

    public static class MaxNumberUDAFEvaluator implements UDAFEvaluator{
        private IntWritable result;
        public void init() {
            result = null;
        }

        // 聚合的多行中每行的被聚合的值都会被调用 interate 方法,所以这个方法里面我们来定义聚合规则
        public boolean iterate(IntWritable value){
            if(value == null){
                return false;
            }
            if(result == null){
                result = new IntWritable(value.get());
            }else{
                // 需求是求出流量最大值,在这里进行流量的比较,将最大值放入 result
                result.set(Math.max(result.get(), value.get()));
            }
            return true;
        }

        //hive 需要部分聚合结果时会调用该方法,返回当前的 result 作为 hive 取部分聚合值得结果
        public IntWritable terminatePartial(){
            return result;
        }

        // 聚合值,新行未被处理的值会调用 merge 加入聚合,这里直接调用上面定义的聚合规则方法 iterate
        public boolean merge(IntWritable other){
            return iterate(other);
        }

        //hive 需要最后总聚合结果时调用的方法,返回聚合的最终结果
        public IntWritable terminate(){
            return result;
        }
    }
}

导出 jar 包,上传到 Linux 服务器…

Step 1: add jar‘jar-path’

Step 2: create function maxflow as‘包名 + 类名’
Hive 自定义函数 UDF、UDTF、UDAF 入门

Step 3: 使用该函数
Hive 自定义函数 UDF、UDTF、UDAF 入门
于是此时,hive 便会将 sql 语句转换为 mapreduce 任务去执行了。
Hive 自定义函数 UDF、UDTF、UDAF 入门

当我们创建函数之后,得出的结果却不是想要的结果的时候,我们将 Java 代码修改之后,重新打了包上传过来,也重新加到了 hive 的 classpath 中,但是新创建出来的函数得出的结果跟修改之前的一样。这个因为新修改过后的类名与之前的类名重复了,在当前 session 中会优先以之前的来创建函数。此时有两种办法解决,一是断开当前的连接,重新使用 beeline 客户端登陆一次,还有就是将修改后的 Java 类改一个名称,重新导入,使用新的 Java 类来创建函数。

当然,这些才都只是 UDF 的小皮毛,我们可以发现,通过自定义函数,我们可以省去写很多 sql,并且通过使用 api,我们可以更随意的操作数据库里的字段,实现多种计算和统计。

Hive 编程指南 PDF 中文高清版  https://www.linuxidc.com/Linux/2015-01/111837.htm
基于 Hadoop 集群的 Hive 安装 https://www.linuxidc.com/Linux/2013-07/87952.htm
Hive 内表和外表的区别 https://www.linuxidc.com/Linux/2013-07/87313.htm
Hadoop + Hive + Map +reduce 集群安装部署 https://www.linuxidc.com/Linux/2013-07/86959.htm
Hive 本地独立模式安装 https://www.linuxidc.com/Linux/2013-06/86104.htm
Hive 学习之 WordCount 单词统计 https://www.linuxidc.com/Linux/2013-04/82874.htm
Hive 运行架构及配置部署 https://www.linuxidc.com/Linux/2014-08/105508.htm
Hive 2.1.1 安装配置详解  https://www.linuxidc.com/Linux/2017-04/143053.htm
Hive 安装及与 HBase 的整合  https://www.linuxidc.com/Linux/2016-12/138721.htm

Hive 的详细介绍:请点这里
Hive 的下载地址:请点这里

正文完
星哥说事-微信公众号
post-qrcode
 
星锅
版权声明:本站原创文章,由 星锅 2022-01-22发表,共计7678字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
【腾讯云】推广者专属福利,新客户无门槛领取总价值高达2860元代金券,每种代金券限量500张,先到先得。
阿里云-最新活动爆款每日限量供应
评论(没有评论)
验证码
【腾讯云】云服务器、云数据库、COS、CDN、短信等云产品特惠热卖中