Hive自身查詢語言HQL能完畢大部分的功能,但遇到特殊需求時,須要自己寫UDF實現。下面是一個完整的案例。
1、eclipse中編寫UDF
①項目中增加hive的lib下的全部jar包和Hadoop中share下hadoop-common-2.5.1.jar(Hadoop眼下最新版本號2.5.1)。②UDF類要繼承org.apache.hadoop.hive.ql.exec.UDF類。類中要實現evaluate。
當我們在hive中使用自己定義的UDF的時候,hive會調用類中的evaluate方法來實現特定的功能
③導出項目為jar文件。
注:項目的jdk與集群的jdk要一致。
詳細樣例:
package com.zx.hive.udf;
import org.apache.hadoop.hive.ql.exec.UDF;
public class UdfTestLength extends UDF{ public Integer evaluate(String s) { if(s==null) { return null; }else{ return s.length(); } } }將上面的類打成jar的形式,我使用eclipse直接導出為test-udf.jar包。然后放在/root文件夾中。
2、自己定義函數調用過程:
①加入jar包(在hive命令行里面運行)hive> add jar /root/test-udf.jar;
②創建暫時函數 ,hive命令行關閉后,即失效。
hive> create temporary function testlength as ‘com.zx.hive.udf.UdfTestLength';
③調用
hive> select id, name, testlength(name) from student;
④將查詢結果保存到HDFS中
hive> create table result row format delimited fields terminated by '\t' as select id,testlength(nation) from student;
(轉載請注明,很多其它內容見:http://blog.csdn.net/hwwn2009/article/details/41289197)
3、遇到的問題:
①須要引用第三方包,有兩種方式:
1)在執行hive hql時,手動將udf所須要的jar包通過add語句加入:add jar /root/***.jar(測試通過)。
2)安裝eclipse 插件:fatjar (測試通過)
在線安裝fatjar:
eclipse菜單條 help >software updates >Search for new features to install>new update site>
填寫name 和url
name:隨意起個, 就寫fat吧
url:這個是fat jar的地址 輸入http://kurucz-grafika.de/fatjar
使用fatjar打包的方法:
②程序須要讀取外部資源
首先外部資源要在UDF執行之前加入,使用命令add file [file]在hive中進行暫時注冊。
UDF中內部調用的文件地址直接用本地文件地址表示。
比如: String filepath = "/home/dev/test/test.txt";上傳至hive之后。外部文件地址僅僅需改成String filepath = "./test.txt";就可以。
(轉載請注明,很多其它內容見:http://blog.csdn.net/hwwn2009/article/details/41289197)