zoukankan      html  css  js  c++  java
  • hive利器 自定义UDF+重编译hive

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

    01 import org.apache.hadoop.hive.ql.exec.UDF;
    02  
    03 public class NewIP2Long extends UDF {
    04     public static long ip2long(String ip) {
    05  
    06         String[] ips = ip.split("[.]");
    07         long ipNum = 0;
    08         if (ips == null) {
    09             return 0;
    10         }
    11         for (int i = 0; i < ips.length; i++) {
    12             ipNum = ipNum << Byte.SIZE | Long.parseLong(ips[i]);
    13         }
    14  
    15         return ipNum;
    16     }
    17  
    18     public long evaluate(String ip) {
    19         if (ip.matches("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}")) {
    20             try {
    21                 long ipNum = ip2long(ip);
    22                 return ipNum;
    23             } catch (Exception e) {
    24                 return 0;
    25             }
    26         } else {
    27             return 0;
    28         }
    29     }
    30  
    31     public static void main(String[] argvs) {
    32         NewIP2Long ipl = new NewIP2Long();
    33         System.out.println(ip2long("112.64.106.238"));
    34         System.out.println(ipl.evaluate("58.35.186.62"));
    35     }
    36 }

    2.编译,然后打包成ip2long.jar。
    3.在需要使用ip2long这个方法到时候:

    1 add jar /tmp/NEWIP2Long.jar;
    2 drop temporary function ip2long;
    3 create temporary function ip2long as 'NewIP2Long';//如果类有包名,要加上包名
    4 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/

    1 cd  ~/install/hive-0.8.1/src/ql/src/java/org/apache/hadoop/hive/ql/udf/
    2 ls -lhgt |head

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

    1 import com.meilishuo.hive.udf.UDFIp2Long;   //添加import
    2  
    3 registerUDF("ip2long", UDFIp2Long.class, false); //添加register

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

    1 cd ~/install/hive-0.8.1/src
    2 ant -Dhadoop.version=1.0.1 package

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

    1 cp hive-exec-0.8.1.jar /hadoop/hive/lib/hive-exec-0.8.1.jar.0628
    2 rm hive-exec-0.8.1.jar
    3 ln -s hive-exec-0.8.1.jar.0628 hive-exec-0.8.1.jar

      5)重启hive服务
      6)测试

  • 相关阅读:
    Redis
    Linux 命令
    Linux 命令
    Networking
    Networking
    MySQL(5.6) 函数
    MySQL 中事务、事务隔离级别详解
    程序人生:搜索引擎被禁用,你还会写代码吗?
    程序人生:搜索引擎被禁用,你还会写代码吗?
    程序员幽默:老板让明天带条鱼来大家观察
  • 原文地址:https://www.cnblogs.com/end/p/2849828.html
Copyright © 2011-2022 走看看