hive利器 自訂UDF+重編譯hive

來源:互聯網
上載者:User

用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)測試

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.