您的位置:首页 > 其它

Hive UDF开发-简介

2017-02-20 11:38 218 查看
Hive进行UDF开发十分简单,此处所说UDF为Temporary的function,所以需要hive版本在0.4.0以上才可以。Hive的UDF开发只需要重构UDF类的evaluate函数即可。例:package com.hrj.hive.udf;import org.apache.hadoop.hive.ql.exec.UDF;public class helloUDF extends UDF {public String evaluate(String str) {try {return "HelloWorld " + str;} catch (Exception e) {return null;}}}将该java文件编译成helloudf.jarhive> add jar helloudf.jar;hive> create temporary function helloworld as 'com.hrj.hive.udf.helloUDF';hive> select helloworld(t.col1) from t limit 10;hive> drop temporary function helloworld;注:1.helloworld为临时的函数,所以每次进入hive都需要add jar以及create temporary操作2.UDF只能实现一进一出的操作,如果需要实现多进一出,则需要实现UDAF转自: http://www.cnblogs.com/end/archive/2012/10/12/2721543.html
除此之外,我们也可以创建非临时的UDF,然后将其部署到服务器上。

1 编写UDF类

以简单的处理单个字段的UDF函数为例,开发自定义UDF函数需要继承’org.apache.hadoop.hive.ql.exec.UDF’类.可以通过Maven添加,pom文件中加入(版本号跟Hive版本一致即可):
<dependency>
<groupId>org.apache.hive</groupId>
<artifactId>hive-exec</artifactId>
<version>0.13.1</version>
</dependency>
最简单的实现只需继承UDF类,并实现evaluate函数.如下UDF函数用来将IP(v4)地址转换为整数.
package com.liam8.hive;

import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.exec.UDF;

/**
* Convert IPv4 to a num which type is Long in java.
* Created by Liam on 2016/4/11.
*/
@Description(name = "IpToNum", value = "_FUNC_(ip) - Convert IPv4 to a num(long).")
public class IpToNum extends UDF {

public long evaluate(String ip) {
String[] nums = ip.split("\\.");
return Long.parseLong(nums[3]) + Long.parseLong(nums[2]) * 256
+ Long.parseLong(nums[1]) * 65536 + Long.parseLong(nums[0]) * 16777216;
}

}
evaluate方法的输入输出即是UDF函数的输入输出.Description注解部分提供函数的帮助信息.执行:desc function test.iptonum输出:test.iptonum(ip) - Convert IPv4 to a num(long).源码已上传 Github

2 部署及创建UDF函数

PS:Hive0.13及以后版本适用

部署jar包

将jar包复制到HDFS.
hdfs -dfs -put udfs-0.1.jar 'hdfs:///user/hadoop/hiveUDF'

创建永久函数

需在Hive中执行sql语句,格式如下:
CREATE FUNCTION [db_name.]function_name AS class_name
[USING JAR|FILE|ARCHIVE 'file_uri' [, JAR|FILE|ARCHIVE 'file_uri'] ];
如:
create function test.iptonum as 'com.liam8.hive.IpToNum' using jar 'hdfs:///user/hadoop/hiveUDF/udfs-0.1.jar'
函数需要属于某个库,如这里是’test’,当其他库调用时,需要加上库名,如’test.iptonum’.调用方式:
select test.iptonum('127.0.0.1');

创建临时函数

临时函数只在当前session中有效,临时函数不能指定库.
create temporary function iptonum as 'com.liam8.hive.IpToNum' using jar 'hdfs:///user/hadoop/hiveUDF/udfs-0.1.jar'
调用方式:
select iptonum('127.0.0.1');

4 参考资料

LanguageManualDDL-PermanentFunctionsHivePlugins原文地址:http://liam8.ml/2016/04/11/add-udf-to-hive/版权声明:转载请注明出处:http://blog.csdn.net/liam08

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: