常见的自定义函数有那些: udf:用户自定义函数,user defined function.一对一的输入输出。(经常使用) udaf:用户自定义聚合函数,user defined agregation function。多对以输入输出。 udtf:用户自定义表生成函数,user defined table-generate function。一对多的输入输出。
编写udf的方式: 1、继承UDF,重写evaluate(),允许重载。 2、继承genericUDF,重写initlizer()、getDisplay()、evaluate().
pom依赖:
<property> <name>hive.aux.jars.path</name> <value>$HIVE_HOME/auxlib</value> <description>The location of the plugin jars that contain implementations of user defined functions and serdes. </description> </property>java代码:
import org.apache.directory.api.util.Strings; import org.apache.hadoop.hive.ql.exec.UDF; public class FirstUDF extends UDF { public static String evaluate(String str){ if(Strings.isEmpty(str)){ return null; } return Strings.toLowerCase(str); } }方便的测试方法: create table dual(id string); insert into dual values(' '); 调用函数进行测试。 select lowcase('XXXXXX') from dual;
使用方法: 第一种:(只对当前session有效) 1、将编写好的 udf编译上传到服务器,并添加到hive的classpath中: hive> add jar /root/GP1707Demo-1.0-SNAPSHOT.jar;
2、创建一个临时函数名 hive> create temporary function lowCase as 'com.qfedu.bigdata.hiveUDF.FirstUDF';
3、查看函数是否注册成功 hive> show functions;
4、测试函数 hive> select lowcase('GAOYUANYUAN') from dual;
输出:gaoyuanyuan
5、删除函数 hive> drop [temporary] function lowCase;
6、删除jar包 hive> delete jar /root/GP1707Demo-1.0-SNAPSHOT.jar;
第二种(只对本session有效) 1、将编译好的udf的jar上传服务器 2、编译一个配置文件: vi ./hive-init hive> add jar /root/GP1707Demo-1.0-SNAPSHOT.jar; hive> create temporary function lowCase as 'com.qfedu.bigdata.hiveUDF.FirstUDF';
3、启动hive时使用配置文件 hive -i ./hive-init
4、测试函数 hive> select lowCase('JIAJINGWEN') from gp1707.dual;
第三种:(临时加载函数) 1、将编译好的udf的jar上传服务器 2、编译一个配置文件,在hive的安装目录下的bin目录下创建一个我文件,文件名.hiverc: vi bin/.hiverc hive> add jar /root/GP1707Demo-1.0-SNAPSHOT.jar; hive> create temporary function lowCase as 'com.qfedu.bigdata.hiveUDF.FirstUDF';
第四种: 编译源码(费劲) 1)将写好的Java文件拷贝到~/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)重启进行测试