zoukankan      html  css  js  c++  java
  • hive使用UDF函数

    UDF几个相关概念:

        UDF: one-to-one row mapping : upper substr【进来一行出去一行】

        UDAF: Aggregation   Many-to-one row mapping   比如sum/min【进来多行出去一行】

        UDTF: Table-generating  one-to-many    比如:lateral view explode()【一对多】

    编写UDF函数测试代码:

    1. 添加依赖

    pod.xml添加hive相关的依赖:

            <dependency>
                <groupId>org.apache.hive</groupId>
                <artifactId>hive-exec</artifactId>
                <version>2.3.4</version>
            </dependency> 

    2. ZeroifNull类

    udf的功能:如果字段为null时,将值改为null,不为null则输出原值

    创建一个ZeroifNull类继承UDF,并且重写evaluate方法

    public class ZeroifNull extends UDF {
        public String evaluate(String input) {
            //TODO...此处为开发业务逻辑的地方
            return Optional.ofNullable(input).orElse("0");
        }
    
        public static void main(String[] args) {
            ZeroifNull zeroifNull = new ZeroifNull();
            String evaluate = zeroifNull.evaluate(null);
            System.out.println(evaluate);
        }
    }

    3. 打jar包

    在idea中用maven打包后,上传到hive服务器;包名为:zeroifnull-1.0-SNAPSHOT.jar

    创建函数

    可以创建临时函数或者永久函数:

    create temporary function zero_if_null as 'com.ht706.hive.udf.ZeroifNUll';
    create function zero_if_null as 'com.ht706.hive.udf.ZeroifNull';

    方法一:创建临时函数(Temporary Functions)

      添加jar包:

     add jar /opt/zeroifnull-1.0-SNAPSHOT.jar;

    创建函数:

    create temporary function zero_if_null  as 'com.ht706.hive.udf.ZeroifNull';

    方法二:无需手动add jar包

        在hive的家目录下创建auxlib目录,把jar包放在此目录下即可;

        不管创建临时函数,还是持久函数,把jar放入auxlib后就无需手动进行加载;

    方法三:创建持久函数(Permanent Functions)

    创建函数:

    CREATE FUNCTION zero_if_null AS 'com.ht706.hive.udf.ZeroifNull';

    方法四:创建持久函数(Permanent Functions),并且使用hdfs上的jar;生产建议此种方式

     将jar包放在hdfs上;

    hdfs dfs -put /opt/zeroifnull-1.0-SNAPSHOT.jar /hive/lib

    创建函数:

    CREATE FUNCTION zero_if_null AS 'com.ht706.hive.udf.ZeroifNull' USING JAR 'hdfs://hadoop:9000/hive/lib/zeroifnull-1.0-SNAPSHOT.jar';

    总结:可以编写一些如zero_if_null, 或者将字符串的开始下标到结束下标 变成xxx(mask)或者一些字段类型转换的函数。 

  • 相关阅读:
    iOS屏幕旋转
    iOS使用NSURLSession发送POST请求,后台无法接受到请求过来的参数
    iOS NET Error Code
    Android App在Google App Store中搜不到
    postman中 form-data、x-www-form-urlencoded、raw、binary的区别
    Android的缓存图片不在系统图库中显示的解决办法
    Android的Notification相关设置
    iOS+PHP图片上传
    解决ndk编译lua时遇到 undefined reference to '__srget'的问题
    避免修改Android.mk添加cpp文件路径
  • 原文地址:https://www.cnblogs.com/erlou96/p/14329332.html
Copyright © 2011-2022 走看看