Hive UDF函数编写流程详解


常用命令:

SHOW FUNCTIONS;      查看hive函数
DESCRIBE FUNCTION <function_name>;    查看hive某个函数的用法
DESCRIBE FUNCTION EXTENDED <function_name>;  查看hive某个函数更详细的用法

UDF编写步骤
一、使用IDEA创建maven工程,步骤:File-》New-》Project-》Maven-》maven-archetype-quickstart-》输入maven坐标完成maven工程创建
二、pom.xml中添加如下依赖
< properties >
  < project.build.sourceEncoding > UTF-8 </ project.build.sourceEncoding >
  < hadoop.version > 2.6.0-cdh5.12.1 </ hadoop.version >
  < hive.version > 1.1.0-cdh5.12.1 </ hive.version >
</ properties >

<!--CDH版本需要添加repository,apache版本不需要-->
< repositories >
  < repository >
    < id > cloudera </ id >
    < url > https://repository.cloudera.com/artifactory/cloudera-repos/ </ url >
  </ repository >
</ repositories >


< dependencies >
  <!--添加Hadoop依赖-->
  < dependency >
    < groupId > org.apache.hadoop </ groupId >
    < artifactId > hadoop-common </ artifactId >
    < version > ${hadoop.version} </ version >
  </ dependency >

  <!--添加Hive依赖-->
  < dependency >
    < groupId > org.apache.hive </ groupId >
    < artifactId > hive-exec </ artifactId >
    < version > ${hive.version} </ version >
  </ dependency >
</ dependencies >

三、编写Hive UDF函数
新建一个类继承UDF类并重写evaluate方法,示列代码如下:
public class  HelloUDF  extends  UDF{
    public  Text evaluate( final  Text s) {
        if  (s ==  null ) {  return null ; }
        return new  Text( "Hello:" + s);
    }

    public static void  main(String[] args) {
        HelloUDF udf =  new  HelloUDF();
        Text result = udf.evaluate( new  Text ( "Hive" ));
        System. out .println(result.toString());
    }
}
四、打包编译生成jar包,注册UDF函数
生成的jar包如:hive-1.0.jar
(1)临时生效,即只在当前hive shell环境生效
hive> add jar hive-1.0.jar;     加入jar包,注意jar包的路径,我这里是当前路径
Added [hive-1.0.jar] to class path
Added resources: [hive-1.0.jar]
hive> list jars;   查看加入的jar包
hive-1.0.jar
hive>  create temporary function hive_hello as 'com.mycompany.bda.UdfHello';   创建临时函数
hive>  show functions;   查看函数,可知增加了函数hive_hello
hive> select hive_hello( fundaccount ) from xx limit 3;  验证:函数使用,蓝色部分换成自己的表和表字段

(2)永久有效,可以在多hive shell回话窗口使用udf函数
把jar包上传到hdfs,路径如下:
[root@bda5 ]# hadoop fs -ls hdfs://nameservice-ha/tzt/
-rw-r--r--   2 root root       2844 2018-01-18 10:03 hdfs://nameservice-ha/tzt/hive-1.0.jar
hive> CREATE FUNCTION addhello AS  ' com.mycompany.bda.UdfHello '   USING JAR  ' hdfs://nameservice-ha/tzt/hive-1.0.jar ' ;  蓝色部分改成自己的路径

函数验证:
hive> select addhello('hive') from xx limit 3;     
hive> show functions;   可知多了一个函数 default.addhello,default为当前使用的数据库
另外也可以查看hive元数据库表 select * from FUNCS;新增了一个函数addhello

五、Hive注册UDF函数如何在Impala中使用
在impala-shell中刷新一下元数据即可,使用命令
invalidate metadata;

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值