0. 环境
Java 1.8.0
Hive 1.1
gradle 5.6.4
引入依赖:
compileOnly 'org.apache.hive:hive-exec:1.1.1' compile 'org.apache.hadoop:hadoop-common:2.7.1'
曾经碰到的错误:
Could not find org.pentaho:pentaho-aggdesigner-algorithm:5.1.5-jhyde.
Searched in the following locations:
- https://repo.maven.apache.org/maven2/org/pentaho/pentaho-aggdesigner-algorithm/5.1.5-jhyde/pentaho-aggdesigner-algorithm-5.1.5-jhyde.pom
- https://repo.maven.apache.org/maven2/org/pentaho/pentaho-aggdesigner-algorithm/5.1.5-jhyde/pentaho-aggdesigner-algorithm-5.1.5-jhyde.jar
Required by:
project : > org.apache.hive:hive-exec:1.1.1 > org.apache.calcite:calcite-core:1.0.0-incubating
加入maven repository
repositories { mavenCentral() // fix: Could not find org.pentaho:pentaho-aggdesigner-algorithm:5.1.5-jhyde. maven { url "https://public.nexus.pentaho.org/repository/proxy-public-3rd-party-release/" } }
1. 定义自己的函数
package
com.example.hive.udf;
import org.apache.hadoop.hive.ql.exec.UDF; import org.apache.hadoop.io.Text; public class SayHello extends UDF { public Text evaluate(final Text s) { if (s == null) { return null; } return new Text("Hello " + s.toString()); } }
打包,上传到HDFS某路径,例如/user/hive/udf/sayHello.jar
2. 创建临时函数
若函数仅仅是自己使用,不需要全局共享,则创建临时函数,session关闭后失效。注意:临时函数不需要指定database。
--1. add dependency to your application classpath
add jar hdfs://nameservice/user/hive/udf/sayHello.jar--2. create temporary function
create temporary function sayHello as 'com.example.hive.udf.SayHello'
也可以使用一句实现相同的功能
CREATE TEMPORARY FUNCTION sayHello as 'com.example.hive.udf.SayHello' USING JAR 'hdfs://nameservice/user/hive/udf/sayHello.jar'
测试:
select sayHello("Adore")
3. 创建全局函数
若是自定义的函数需要全局共享,则使用下面的方式创建。这里的函数需要指定database名称,若不指定默认使用当前数据库。
create function default.sayHello as 'com.example.hive.udf.SayHello'
USING JAR 'hdfs://nameservice/user/hive/udf/sayHello.jar'
新打开一个窗口测试:【使用不同的session】
select sayHello("Adore")
参考文献:
https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DDL#LanguageManualDDL-CreateFunction
https://cwiki.apache.org/confluence/display/Hive/HivePlugins
https://www.cnblogs.com/yxym2016/p/13218026.html