1、hive自定义函数
hive内置函数虽然丰富,但并不能全部覆盖实际生产所有需求,故需用户自定义函数来满足自身的需求。
1、使用maven创建一个Scala项目
2、继承UDF类
3、重写evaluate
- 引入pom依赖
<dependency>
<groupId>org.apache.hive</groupId>
<artifactId>hive-exec</artifactId>
<version>2.1.1-cdh6.2.0</version>
<!--<scope>provided</scope>-->
</dependency>
注意版本号依据自己实际情况修改。
- 继承UDF类
package com.bw.hive.udf
import org.apache.commons.lang3.StringUtils
import org.apache.hadoop.hive.ql.exec.UDF
object GetHashCode {
}
class GetMainColsHash extends UDF {}
- 重写evaluate方法
package com.bw.hive.udf
import org.apache.commons.lang3.StringUtils
import org.apache.hadoop.hive.ql.exec.UDF
object GetHashCode {
def evaluate(a: String, b: String): String = {
val cols = checkBlank(a) + checkBlank(b)
cols.hashCode.toString
}
private def checkBlank(str: String): String = {
if (StringUtils.isBlank(str)){
""
}else{
str
}
}
def main(args: Array[String]): Unit = {
val (a, b) = ("哈哈", "没问题!")
val result = evaluate(a, b)
println(result)
}
}
class GetMainColsHash extends UDF {}
注意:这里的main方法主要用来自己测试逻辑是否正确。
- 打jar包上传至集群
2、临时自定义函数(只对当前session有效)
- 添加jar包(临时自定义函数不需要上传至hdfs)
(假设jar包名为:hiveUDF-1.0.jar;上传至/home/hadoop/lib/hiveUDF-1.0.jar)
hive> add jar /home/hadoop/lib/hiveUDF-1.0.jar;
- 自定义临时函数:
create temporary function getHashCode as 'com.bw.hive.udf.GetHashCode';
- 测试自定义临时函数:
hive> select getHashCode("哈哈", "没问题!");
3、永久自定义函数
- 上传jar包至hdfs
hadoop -fs -put /home/hadoop/lib/hiveUDF-1.0.jar /user/hiveudf/
- 创建永久函数
create function getHashCode as 'com.baiwang.hive.udf.GetHashCode' using jar 'hdfs:///user/hiveudf/hiveUDF-1.0.jar';
- 测试永久自定义函数
hive> select getHashCode("哈哈", "没问题!");
注意:默认函数添加在default库里,如果要指定库,在函数名前加库名,例如:mydb.getHashCode,此时,该函数只能在mydb库下使用。