官方教程:https://cwiki.apache.org/confluence/display/Hive/HivePlugins
简单使用查看上面官方的文档即可。这里记录一下我使用的实践和一点注意事项。
一 编写udf
这里的需求是写一个udf,用于将经纬度转换成geohash。参数有 经纬度和geohash的精度。
gradle配置
gradle 部分配置如下:
dependencies {
compile group: 'ch.hsr', name: 'geohash', version: '1.3.0'
compileOnly group: 'org.apache.hive', name: 'hive-exec', version: '2.3.6'
}
task fatJar(type: Jar) {
//baseName = project.name
baseName = 'hiveFunction'
project.fileTree("$buildDir/fatjar/libs").forEach { jarFile ->
from zipTree(jarFile )
}
with jar
destinationDir = file("$buildDir/fatjar")
}
task copyToLib(type: Copy) {
into "$buildDir/fatjar/libs"
from configurations.runtime
}
UDF类
GeoHashUDF.java 代码如下:
这里需要注意的就是注释的写法,以及异常的处理。
因为在hive执行的过程中,如果udf抛一个异常出来,有可能会导致整个hive sql执行的失败。所以,对于业务异常,应该避免向外抛出。
以本geohash的udf为例,如果给定的经纬度不合法,则可返回用0填充的默认字符串。
import ch.hsr.geohash.GeoHash;
import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.exec.U