Hive自定义函数
自定义函数的三种类型:
UDF
输入单行,输出单行(最为常用)
类似Hive自带的部分函数,如substr
例子:select substr(name,0,2) from order3;
要求自定义类继承UDF,重写evaluate方法。
UDTF
user define table-gen function,输入单行,输出多行,类似于 explode(array);
UDAF
user define aggr function,输入多行,输出单行,类似于 sum(xxx)
自定义UDF函数定义及调用过程:
自定义两个函数
1.根据身份证号获取对应省份
2.根据身份证号获取对应年龄段
package com.qiku.udf;
import java.util.HashMap;
import org.apache.hadoop.hive.ql.exec.UDF;
public class ProvinceDemo extends UDF{
static HashMap<String, String> profinceMap = new HashMap<String, String>();
static {
profinceMap.put("11", "北京");profinceMap.put("12", "天津");profinceMap.put("13", "河北");profinceMap.put("14", "山西");profinceMap.put("15", "内蒙");
profinceMap.put("21", "辽宁");profinceMap.put("22", "吉林");profinceMap.put("23", "黑龙江");
profinceMap.put("31", "上海");profinceMap.put("32", "江苏");profinceMap.put("33", "浙江");profinceMap.put("34", "安徽");profinceMap.put("35", "福建");profinceMap.put("36", "江西");profinceMap.put("37", "山东");
profinceMap.put("41", "河南");profinceMap.put("42", "湖北");profinceMap.put("43", "湖南");profinceMap.put("44", "广东");profinceMap.put("45", "广西");profinceMap.put("46", "海南");
profinceMap.put("50", "重庆");profinceMap.put("51", "四川");profinceMap.put("52", "贵州");profinceMap.put("53", "云南");profinceMap.put("54", "西藏");
profinceMap.put("61", "陕西");profinceMap.put("62", "甘肃");profinceMap.put("63", "青海");profinceMap.put("64", "宁夏");profinceMap.put("65", "新疆");
profinceMap.put("71", "台湾");
}
public String evaluate(String idNumber) {
String proId = idNumber.substring(0,2);
return profinceMap.get(proId)!=null?profinceMap.get(proId):"无效的身份信息";
}
public static void main(String[] args) {
String id = "410521198812153217";
ProvinceDemo one = new ProvinceDemo();
System.out.println(one.evaluate(id));
}
}
3.导出对应的jar包(瘦包即可)
4.拷贝瘦包到hive客户端机器目录:
5.hive>add jar /opt/mysoft/hhh.jar
创建临时函数或者永久函数
hive> create temporary function getage as ‘com.qiku.udf.AgeDemo’; //临时函数
hive> create function getage as ‘com.qiku.udf.AgeDemo’; //永久函数
查看当前数据库下所有可用的函数(系统自带的和自己定义的): show functions;
6.调用
hive>select name,getage(idcard) from invt;