1. 在Hive中给我们内置了很多函数
进入hive客户端,查看hive内置函数:
hive > show functions;
OK
!
!=
%
&
*
+
-
/
<
<=
<=>
<>
=
==
>
>=
^
abs
acos
add_months
and
array...
查看函数的具体方法:
hive> DESCRIBE FUNCTION case;
OK
CASE a WHEN b THEN c [WHEN d THEN e]* [ELSE f] END - When a = b, returns c; when a = d, return e; else return fhive> DESCRIBE FUNCTION EXTENDED case;
hive> DESCRIBE FUNCTION EXTENDED case;
OK
CASE a WHEN b THEN c [WHEN d THEN e]* [ELSE f] END - When a = b, returns c; when a = d, return e; else return f
Example:
SELECT
CASE deptno
WHEN 1 THEN Engineering
WHEN 2 THEN Finance
ELSE admin
END,
CASE zone
WHEN 7 THEN Americas
ELSE Asia-Pac
END
FROM emp_de
tails
2. hive函数除了内置还可以自定义
自定义函数开发UDF:
1. 使用maven创建一个java项目
2. 继承UDF类;
3. 重写evaluate方法
创建一个UrlDecodeWithChar类继承UDF,并且重写evaluate方法
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.hadoop.io.Text;public class UrlDecodeWithChar extends UDF{
public Text evaluate(Text param, Text charset) {
if (charset == null || charset.toString().length() == 0) {
charset = new Text("UTF-8");
}
String decode = null;
if (param == null) {
return param;
} else {
String str = param.toString();
try {
decode = URLDecoder.decode(str, charset.toString());
} catch (UnsupportedEncodingException e) {
decode = param.toString();
}
}
return new Text(decode);
}
}
将写好的代码打成jar包.
创建临时函数时:
1. 将jar包放在linux某个目录下,eg: /home/urldecode.jar
2. 进入hive客户端,如下操作:
a) add jar /home/urldecode.jar;
b). create temporary function urldecode as 'com.jobs.main.UrlDecodeWithChar';
临时函数生成(只对当前session有效).
查询结果:
hive > select 'Bom',urldecode('%E5%B9%BF%E5%B7%9E%E5%B8%82%E7%BB%BF%E7%9B%88%E6%B1%BD%E8%BD%A6%E6%9C%8D%E5%8A%A1%E6%9C%89%E9%99%90%E5%85%AC%E5%8F%B8') from ls limit 2;
Bom 广州市绿盈汽车服务有限公司
Bom 广州市绿盈汽车服务有限公司
查看jar包
hive> list jar;
查看自定义函数
hive> show functons;
删除自定义函数
hive> drop functon urldecode;
生成永久函数
1. 需要将jar包上传到hdfs上面
eg: hdfs dfs -put /home/urldecode.jar /usr/lib
2. 创建永久函数
create function urldecode as 'com.jobs.main.UrlDecodeWithChar' using jar 'hdfs:///usr/lib';
注意:执行这条语句创建永久函数,show functiuons 会加上默认的数据库名在函数名前。(default.urldecode )