自定义函数:内置函数无法满足所有的业务场景
hive提供了许多模块的自定义功能。比如serde,自定义函数、输入输出格式等
常见的自定义函数
UDF:user defined function
UDTF:user defined table-generate function ,一对多的输入输出(explode)
UDAF:user defined agregation function,用户自定义聚合函数
编写UDF的方式:
1、继承UDF类、重写evaluate方法,允许重载
2、继承geniricUDF,重写intilizer()、getDispay()、evaluate()
实现一个自定义的函数:
需求:实现小写转大写。
先加入依赖
<!-- https://mvnrepository.com/artifact/org.apache.hive/hive-exec -->
<dependency>
<groupId>org.apache.hive</groupId>
<artifactId>hive-exec</artifactId>
<version>1.2.1</version>
</dependency>
第一种:(只对当前session有效)
1、将编写好的UDF打包并上传到服务器,并将jar包添加到hive的class path中
hive> add jar /root/mr_demo-1.0.jar;
2、创建一个自定义的临时函数名
hive>create temporary function myUpper as 'hiveudf.FirstUDF';
3、测试
show functions
4、select myupper('a');
第二种方式(永久有效)
1、将编写好的UDF打包并上传到服务器Hive的lib中
2、将jar包上传到hdfs中
hdfs dfs -put /apps/apache-hive-1.2.1-bin/lib/mr_demo-1.0.jar /
最后的/ 说明是本地的hdfs的根目录。
3、创建永久函数。
create temporary function myUpper1 as 'hiveudf.FirstUDF' using jar 'hdfs:///mr_demo-1.0.jar';
4、启动hive则会存在该函数myUpper1。
第三种方式:
编译源码:
1)将写好的Jave文件拷贝到~/install/hive-0.8.1/src/ql/src/java/org/apache/hadoop/hive/ql/udf/
cd ~/install/hive-0.8.1/src/ql/src/java/org/apache/hadoop/hive/ql/udf/
ls -lhgt |head
2)修改~/install/hive-0.8.1/src/ql/src/java/org/apache/hadoop/hive/ql/exec/FunctionRegistry.java,增加import和RegisterUDF
import com.meilishuo.hive.udf.UDFIp2Long; //添加import
registerUDF("ip2long", UDFIp2Long.class, false); //添加register
3)在~/install/hive-0.8.1/src下运行ant -Dhadoop.version=1.0.1 package
cd ~/install/hive-0.8.1/src
ant -Dhadoop.version=1.0.1 package
4)替换exec的jar包,新生成的包在/hive-0.8.1/src/build/ql目录下,替换链接
cp hive-exec-0.8.1.jar /hadoop/hive/lib/hive-exec-0.8.1.jar.0628
rm hive-exec-0.8.1.jar
ln -s hive-exec-0.8.1.jar.0628 hive-exec-0.8.1.jar
5)重启进行测试