Hive的UDF,其实很类似Mysql之类的自定义函数
不过它需要用java来编写,而不是用传统的SQL来完成
实现一个UDF的步骤如下:
实现一个Java Class,继承自UDF 打成jar包,并加入到Hive的ClassPath中 生成自定义函数,执行select 删除刚才创建的临时函数
下面这个UDF,是我给hive的array增加的一个函数
用来判断array中是否包含某个值,hive的标准函数中并没有此功能函数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package com.sohu.hadoop.hive.udf ;
import java.util.* ;
import org.apache.hadoop.hive.ql.exec.UDF ;
import org.apache.hadoop.io.Text ;
import org.apache.hadoop.io.BooleanWritable ;
import org.apache.hadoop.io.Text ;
public final class ArrayContains extends UDF {
public BooleanWritable evaluate( ArrayList< String> arr,Text ele)
{
BooleanWritable rtn = new BooleanWritable( false ) ;
if ( arr == null || arr.size ( ) < 1 )
{
return rtn;
}
try {
String cstr = ele.toString ( ) ;
for ( String str : arr)
{
if ( str.equals ( cstr) )
{
rtn = new BooleanWritable( true ) ;
break ;
}
}
} catch ( Exception e) {
e.printStackTrace ( ) ;
}
return rtn;
}
}
然后执行编译打包:
javac -classpath /opt/hadoop_client/hadoop/hadoop-0.20.2+228-core.jar:/opt/hadoop_client/hive/lib/hive-exec-0.5.0.jar src/com/sohu/hadoop/hive/udf/ArrayContains.java -d build
jar -cvf hadooop-mc-udf.jar -C build .
最后执行Hive QL查询:
hive -e "add jar /opt/ysz/udf/hadooop-mc-udf.jar;drop temporary function array_contains;create temporary function array_contains as 'com.sohu.hadoop.hive.udf.ArrayContains';select suv,channelid from pvlog_pre where array_contains(channelid,'2')"