参考官网:
https://cwiki.apache.org/confluence/display/Hive/HivePlugins 添加hive UDF函数
https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF 可查看hive内置函数
常用命令:
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;
---------------------