温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

hive udf如何自定义

发布时间:2021-12-10 10:27:36 来源:亿速云 阅读:147 作者:小新 栏目:云计算

这篇文章主要介绍hive udf如何自定义,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

用hive也有一段时间里,不过一直没写过相关到日志,因为主要用hive也无非是create table,upload data,CRUD 这几个过程。后来工作中需要用到一些常用到方法,了解到hive中支持UDF(User Define Function),看里一些文章发现UDF到编写也很简单,继承UDF然后重写evaluate方法即可,下面以一个ip2long到方法作为参考。 

1.编写UDF类 

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

public class NewIP2Long extends UDF {

    public static long ip2long(String ip) {

        String[] ips = ip.split("[.]");

        long ipNum = 0;

        if (ips == null) {

            return 0;

        }

        for (int i = 0; i < ips.length; i++) {

            ipNum = ipNum << Byte.SIZE | Long.parseLong(ips[i]);

        }

        return ipNum;

    }

    public long evaluate(String ip) {

        if (ip.matches("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}")) {

            try {

                long ipNum = ip2long(ip);

                return ipNum;

            } catch (Exception e) {

                return 0;

            }

        } else {

            return 0;

        }

    }

    public static void main(String[] argvs) {

        NewIP2Long ipl = new NewIP2Long();

        System.out.println(ip2long("112.64.106.238"));

        System.out.println(ipl.evaluate("58.35.186.62"));

    }

}

2.编译,然后打包成ip2long.jar。 

3.在需要使用ip2long这个方法到时候: 

add jar /tmp/NEWIP2Long.jar;

drop temporary function ip2long;

create temporary function ip2long as 'NewIP2Long';//如果类有包名,要加上包名

select ip2long(ip) from XXX ;

这种方法每次使用都要add,create一下,还是很麻烦,如果能把UDF编译到hive源码中那一定是件很high的事。 

进阶:将自定义UDF编译到hive中

重编译hive: 

  1)将写好的Jave文件拷贝到~/install/hive-0.8.1/src/ql/src/java/org/apache/hadoop/hive/ql/udf/ 

cd  ~/install/hive-0.8.1/src/ql/src/java/org/apache/hadoop/hive/ql/udf/

ls -lhgt |head

  2)修改~/install/hive-0.8.1/src/ql/src/java/org/apache/hadoop/hive/ql/exec/FunctionRegistry.java,增加import和RegisterUDF

import com.meilishuo.hive.udf.UDFIp2Long;   //添加import

registerUDF("ip2long", UDFIp2Long.class, false); //添加register

  3)在~/install/hive-0.8.1/src下运行ant -Dhadoop.version=1.0.1 package

?

1

2

cd ~/install/hive-0.8.1/src

ant -Dhadoop.version=1.0.1 package

  4)替换exec的jar包,新生成的包在/hive-0.8.1/src/build/ql目录下,替换链接    

cp hive-exec-0.8.1.jar /hadoop/hive/lib/hive-exec-0.8.1.jar.0628

rm hive-exec-0.8.1.jar

ln -s hive-exec-0.8.1.jar.0628 hive-exec-0.8.1.jar

  5)重启hive服务 

  6)测试 

以上是“hive udf如何自定义”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI