Hive UDF编程

在该类中加入 evaluate 方法

"evaluate" should never be a void method. However it can return "null" if * needed.

 

 

public class UDFLastDay extends UDF{
	private final SimpleDateFormat inputFormatter = new SimpleDateFormat("yyyy-MM-dd");
	private final SimpleDateFormat outFormatter = new SimpleDateFormat("yyyy-MM-dd");
	
	private final Calendar calendar = Calendar.getInstance();
	
	
	Text result = new Text();
	
	//  2015-03-01  ==> 2015-03-31
	public Text evaluate(Text input) {
		
		if(null == input || StringUtils.isBlank(input.toString())) {
			return null;
		}
		
		try {
			calendar.setTime(inputFormatter.parse(input.toString()));
			int lastDate = calendar.getActualMaximum(Calendar.DATE);  //获得到月份最大的天数
			calendar.set(Calendar.DATE, lastDate);
			
			result.set(outFormatter.format(calendar.getTime()));
			
			return result;
		} catch (ParseException e) {
			e.printStackTrace();
			return null;
		}
	}
}

 

  • 打包放到 linux 某个目录下 例如: /home/hadoop/software/lib/udf.jar 
  • 如何将UDF加入到hive中使用?

方式一:(当前session有效)

add jar /home/hadoop/software/lib/udf.jar ;

create temporary function getLastDay as 'com.cloudyhadoop.bigdata.udf.UDFLastDay';

 

show functions;

select empno, ename, hiredate, getLastDay(hiredate) last_day from emp;

 方式二:(全局有效)

hive-site.xml中添加如下配置信息:

<property>

<name>hive.aux.jars.path</name>

<value>file:///home/hadoop/software/lib/udf.jar</value>

</property>

 

启动hive之后,就不需要再:add jar /home/hadoop/software/lib/udf.jar ;

create temporary function getLastDay as 'com.cloudyhadoop.bigdata.udf.UDFLastDay';

 

temporary:  current session, 退出或者重启之后函数丢失

 

如何做到全局有效?

1、https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DDL#LanguageManualDDL-Create/DropFunction

CREATE FUNCTION [db_name.]function_name AS class_name

  [USING JAR|FILE|ARCHIVE 'file_uri' [, JAR|FILE|ARCHIVE 'file_uri'] ];

2、修改源代码

https://github.com/cloudera/hive/blob/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/FunctionRegistry.java

registerUDF("getLastDay", UDFLastDay.class, false);

重新编译、部署

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值