Hive 自定义函数
来源:互联网 发布:wrecking ball网络歌手 编辑:程序博客网 时间:2024/06/15 20:32
场景描述
现在需要对一个表中的birthday字段做些处理,以便得出用户的星座
解决思路
由于问题比价特殊,无法使用内置函数或者使用特殊的HQL处理,所以问题的基本思路是使用Hive自定义函数来进行操作
脚本编写
编写hive自定义函数
编写一个UDF·,需要继承UDF类并实现evaluate()函数。在查询执行的过程中,查询中每个应用到这个函数的地方都会对这个类进行实例化。对于每行输入都会调用evaluate()函数,处理过后的值返回给Hive。
evaluate方法可以重载,根据类型自动选择匹配的方法
类上可以添加@Description对类进行描述,在Hive中,可以使用 SHOW FUNCTION 来对方法进行描述讲解
编写自定义UDF需要2个包,分别为:hive-exec-2.1.0.jar, hadoop-common-2.7.2.jar
Java代码实现:
package hadoop.hive.custom;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.Date;import org.apache.hadoop.hive.ql.exec.Description;import org.apache.hadoop.hive.ql.exec.UDF;import org.apache.hadoop.hive.ql.parse.HiveParser.recordReader_return;import org.apache.hadoop.io.Text;import org.apache.hadoop.net.SocketOutputStream;@Description( name = "transfer date to constellation", value = "_FUNC_(date) - from input date string", extended = "Example:\n" + "> SELECT _FUNC_(date_string) FROM src;\n" )public class UDFConstellation extends UDF { public Text evaluate(String date){ Date uDate = null; try { uDate = new SimpleDateFormat("yyyy-MM-dd").parse(date); } catch (ParseException e) { e.printStackTrace(); } return new Text(getConstellation(uDate)); } public final String[] constellationArr = {"水瓶座", "双鱼座", "白羊座", "金牛座","双子座", "巨蟹座", "狮子座", "处女座", "天秤座", "天蝎座", "射手座", "魔羯座"}; public final int[] constellationEdgeDay = { 20, 19, 21, 21, 21, 22, 23, 23, 23, 23, 22, 22 }; public String getConstellation(Date date){ if(date == null){ return constellationArr[11]; } Calendar cal = Calendar.getInstance(); cal.setTime(date); int month = cal.get(Calendar.MONTH); int day = cal.get(Calendar.DAY_OF_MONTH); if (day < constellationEdgeDay[month]){ month = month - 1; } if (month >= 0){ return constellationArr[month]; } else { return constellationArr[11]; } }}
把java文件打包成jar文件
右击类 > Export > 选择JAR file > 勾选上.classpath、.project > 选择路径 > finish
存储Hive函数
hive> add jar /usr/local/hive/constellation.jar;Added [/usr/local/hive/constellation.jar] to class pathAdded resources: [/usr/local/hive/constellation.jar]hive>hive> create temporary function constellation as 'hadoop.hive.custom.UDFConstellation';OKTime taken: 0.562 secondshive>
接下来,可以通过show functions 来查看函数是否被加入
也可以 desc function constellation 来查看函数(也就是类中@Description的内容)
注意:在create temporary function constellation as ‘hadoop.hive.custom.UDFConstellation’为类文件的全路径名,
阅读全文
1 0
- 自定义-Hive自定义函数
- Hive 自定义函数函数
- Hive 自定义函数函数
- HIVE中的自定义函数
- hive用户自定义函数
- HIVE中的自定义函数 .
- HIVE中的自定义函数
- HIVE 自定义函数 UDF
- HIVE中的自定义函数
- hive中的自定义函数
- Hive自定义函数
- Hive自定义函数
- Hive自定义函数
- HIVE 自定义函数
- hive 自定义函数扩展
- Hive--自定义函数
- HIVE自定义函数类型
- Hive中自定义函数
- 凸包边上的点求法
- 简单的位运算
- 判断是否构成三角形
- 文献综述——In-Situ Visualization in Fluid Mechanics using Catalyst: A Case Study for Code Saturne
- 在Spring中使用AOP实现日志功能
- Hive 自定义函数
- Quartz动态定时任务管理
- python基础学习三——混合数据类型
- 数据库
- SURF 与 SIFT
- cookie和session
- 使用HTML语言和CSS开发商业站点_表单
- 快速排序
- mysql密码丢失问题解决