博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
hive自定义函数
阅读量:4160 次
发布时间:2019-05-26

本文共 2536 字,大约阅读时间需要 8 分钟。

文章目录

一.hive自定义函数介绍

当hive提供的内置函数无法满足业务需求时,可以考虑使用用户自定义函数(User-Defined Function,UDF)

hive中常见的UDF有如下3种

  • 1)UDF
  • 一条记录使用函数后输出还是一条记录,如:upper/substr
  • 2)UDAS(User-Defined Aggregation Function)
  • 多条记录使用函数后输出还是一条记录,如:count/max等
  • 3)UDTF(User-Defined Table-Generating Functions)
  • 一条记录使用函数后输出多条记录,如:lateral view explore()

二.hive自定义函数开发

1.需求:开发自定义函数,使得在指定字段前加上"Hello: "字样

2.hive中UDF函数开发步骤

  • 1)继承UDF类
  • 2)重写evaluate方法,该方法支持重载,对每条记录执行一次evaluate方法
    注意: 1.UDF必须要有返回值,可以是null,但是不能为void 2.推荐使用Text/LongWritable等hadoop类型

3.功能实现

1)新建maven工程,在pom.xml中添加UDF函数开发的依赖包,如下:

cloudera
https://repository.cloudera.com/artifactory/cloudera-repos/
junit
junit
4.12
test
org.apache.hadoop
hadoop-common
2.6.0
org.apache.hive
hive-exec
1.1.0
org.apache.hive
hive-jdbc
1.1.0

2)自定义UDF函数实现

package sunyong.hive;import org.apache.hadoop.hive.ql.exec.UDF;import org.apache.hadoop.io.Text;/** * @author sunyong * @date 2020/07/12 * @description * 功能:输入xxx 输出:Hello: xxx */public class HelloUDF extends UDF {
public Text evaluate(Text name){
return new Text("Hello : "+name); } public static void main(String[] args) {
HelloUDF udf = new HelloUDF(); System.out.println(udf.evaluate(new Text("张三"))); }}

3)编译jar包上传到linux本地hive的lib目录下

4)将自定义UDF函数添加到hive中去,即在hive命令行模式中执行如下命令:add jar /opt/install/hive/lib/UDF.jar;

#语法add jar jar包绝对路径名;

5)创建函数(若在function前面有temporary,表示临时函数退出会话将会删除该函数):create function sayHello as 'sunyong.hive.HelloUDF';

#语法create [temporary] function sayHello as '全类名(包名.类名)';

6)使用函数:select sayHello(emp_name) from employee;,效果如下:

在这里插入图片描述

4.碰到的坑:可正常添加jar包却无法创建函数

hive> create temporary function sayHello as "sunyong.hive.HelloUDF";FAILED: Class HelloUDF not foundFAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.FunctionTask
hive> create function sayHello as 'sunyong.hive.HelloUDF';Failed to register acid_demo.sayhello using class sunyong.hive.HelloUDFFAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.FunctionTask

解决方法:

#下载zip包yum install zip#以下命令会删除先前jar的签名文件(-d后面参数是自己jar包的名字)zip -d UDF.jar 'META-INF/.SF' 'META-INF/.RSA' 'META-INF/*SF'

转载地址:http://tcjxi.baihongyu.com/

你可能感兴趣的文章
Action-Decision Networks for Visual Tracking with Deep Reinforcement Learning
查看>>
Multiple Object Tracking with High Performance Detection and Appearance Feature
查看>>
深度学习入门(上)-第一章 必备基础知识点
查看>>
ubuntu unzip解压时提示错误 解决方法
查看>>
sprintf函数的说明
查看>>
BOOST_TYPEOF和BOOST_AUTO 作用
查看>>
随机森林概述
查看>>
2011十大战略技术
查看>>
大学应该学的软件知识
查看>>
腾讯与360战争背后的云计算阴影
查看>>
腾讯看了会沉默,360看了会流泪
查看>>
李开复:移动互联网机会最大 微博会现最大赢家
查看>>
2006年的IT十大战略技术
查看>>
操作系统介绍
查看>>
Desktop Linux: The Dream Is Dead
查看>>
我的9年IT路
查看>>
任正非:让用户像用电一样享受云计算
查看>>
学习技术的几个境界
查看>>
计算机世界:免费的代价
查看>>
方兴东:中国网站十年
查看>>