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’为类文件的全路径名,