分享

利用eclipse编写自定义hive udf函数

pig2 2014-5-11 21:57:03 发表于 实操演练 [显示全部楼层] 回帖奖励 阅读模式 关闭右栏 7 18401
问题导读:
1.eclipse创建udf的步骤是什么?
2. 如何添加自定义udf_hive.jar到hive?






在做日志分析的过程中,用到了hadoop框架中的hive,不过有些日志处理用hive中的函数处理显得力不从心,就需要用udf来进行扩展处理了

步骤如下:
1  在eclipse中新建java project   hiveudf   然后新建class  package(com.afan)  name(UDFLower)

2  添加jar library  hadoop-0.20.2-core.jar   hive-exec-0.7.0-cdh3u0.jar两个文件到project

3  编写代码

  1. package com.afan;  
  2. import org.apache.hadoop.hive.ql.exec.UDF;  
  3. import org.apache.hadoop.io.Text;  
  4.   
  5. public class UDFLower extends UDF{  
  6.     public Text evaluate(final Text s){  
  7.         if (null == s){  
  8.             return null;  
  9.         }  
  10.         return new Text(s.toString().toLowerCase());  
  11.     }  
  12. }  
复制代码



4  编译输出打包文件为 udf_hive.jar

5 将udf_hive.jar放入配置好的linux系统的文件夹中路径为/home/udf/udf_hive.jar

6 打开hive命令行测试

  1. hive> add jar /home/udf/udf_hive.jar;
  2. Added udf_hive.jar to class path
  3. Added resource: udf_hive.jar
复制代码




创建udf函数
  1. hive> create temporary function my_lower as 'com.afan.UDFLower';
复制代码


创建测试数据
  1. hive> create table dual (info string);
复制代码



导入数据文件data.txt

data.txt文件内容为

WHO

AM

I

HELLO

hive> load data local inpath '/home/data/data.txt' into table dual;

hive> select info from dual;

Total MapReduce jobs = 1
Launching Job 1 out of 1
Number of reduce tasks is set to 0 since there's no reduce operator
Starting Job = job_201105150525_0003, Tracking URL = http://localhost:50030/jobdetails.jsp?jobid=job_201105150525_0003
Kill Command = /usr/local/hadoop/bin/../bin/hadoop job  -Dmapred.job.tracker=localhost:9001 -kill job_201105150525_0003
2011-05-15 06:46:05,459 Stage-1 map = 0%,  reduce = 0%
2011-05-15 06:46:10,905 Stage-1 map = 100%,  reduce = 0%
2011-05-15 06:46:13,963 Stage-1 map = 100%,  reduce = 100%
Ended Job = job_201105150525_0003
OK
WHO
AM
I
HELLO

使用udf函数
hive> select my_lower(info) from dual;
Total MapReduce jobs = 1
Launching Job 1 out of 1
Number of reduce tasks is set to 0 since there's no reduce operator
Starting Job = job_201105150525_0002, Tracking URL = http://localhost:50030/jobdetails.jsp?jobid=job_201105150525_0002
Kill Command = /usr/local/hadoop/bin/../bin/hadoop job  -Dmapred.job.tracker=localhost:9001 -kill job_201105150525_0002
2011-05-15 06:43:26,100 Stage-1 map = 0%,  reduce = 0%
2011-05-15 06:43:34,364 Stage-1 map = 100%,  reduce = 0%
2011-05-15 06:43:37,484 Stage-1 map = 100%,  reduce = 100%
Ended Job = job_201105150525_0002
OK
who
am
i
hello

经测试成功通过

参考文章:eclipse下编写hive的UDF函数


已有(7)人评论

跳转到指定楼层
chinaboy2005 发表于 2014-11-12 16:59:16
正好需要,学习收藏了
回复

使用道具 举报

zzuyao 发表于 2014-12-9 15:02:13
回复

使用道具 举报

EASONLIU 发表于 2014-12-14 20:09:03
很强大,学习了!!!!!!
回复

使用道具 举报

ghzx071458 发表于 2017-5-8 16:05:04
非常不错,感谢楼主分享。
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关闭

推荐上一条 /2 下一条