1.什么是HIVE UDF函数?
hive udf即用户自定义函数(User Defined Function,简称UDF)。当hive系统函数不能满足我们需求的时候,就需要我们通过编码的方式,通过hive实现可以查询的特定功能的函数。
2.HIVE UDF函数如何实现?
只要满足两个要点
- 继承UDF类
- 实现evaluate方法
3.案例(将hive科学计数法转化为数值)
定义一个ScientificNotationTransitionUDF类继承UDF类并实现evaluate方法:
package com.udf;
import org.apache.hadoop.hive.ql.exec.UDF;
import java.math.BigDecimal;
public class ScientificNotationTransitionUDF extends UDF {
//5.0E-4,5.0E4
public String evaluate(String str){
if(str.equals("") || str.equals(" ") || str.equals("null") || str.equals("NULL") || str == null || !str.contains("E")){
return str;
}
String str_transf = new BigDecimal(str).toPlainString();
return str_transf;
}
}
4.部署
(1)package打包,并上传到服务器
(2)添加jar包,创建临时函数
spark-sql> add jar /home/hadoop/jar/learing_java-1.0-SNAPSHOT.jar;
0
Time taken: 0.552 seconds, Fetched 1 row(s)
spark-sql> create temporary function Scientific_Notation_Transition as 'com.udf.ScientificNotationTransitionUDF';
Time taken: 0.019 seconds
5.使用
spark-sql> select Scientific_Notation_Transition('1.2345E6');
1234500
Time taken: 0.76 seconds, Fetched 1 row(s)
spark-sql> select Scientific_Notation_Transition('1.2345E-6');
0.0000012345
Time taken: 0.558 seconds, Fetched 1 row(s)
spark-sql> select Scientific_Notation_Transition('null');
null
Time taken: 0.052 seconds, Fetched 1 row(s)