Hive自定义函数

本文介绍了Hive中的自定义函数,包括UDF、UDTF和UDAF三种类型,并通过实例展示了如何定义和调用自定义函数,如根据身份证号获取省份和年龄段。还详细说明了将自定义函数打包成jar,拷贝到Hive客户端,创建临时和永久函数的步骤,以及如何查看所有可用函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值