hive—UDF操作
udf的操作过程:
在HIVE会话中add自定义函数的jar文件,然后创建function,继而使用函数。
下面就以下面课题为例:
课题:统计每个活动的PV和UV
一、Java通过正则表达式,截取标题名称。
以链接,截取标红的字符串。
http://cms.yhd.com/sale/vtxqCLCzfto?tc=ad.0.0.17280-32881642.1&tp=1.1.36.9.1.LEffwdz-10-35RcM&ti=ZX8H
为例。
核心代码如下,
importjava.util.regex.Matcher;importjava.util.regex.Pattern;importorg.apache.hadoop.hive.ql.exec.UDF;public class GetCommentNameOrId extendsUDF {publicString evaluate(String url,String flag){
String str= null;
Pattern p= Pattern.compile(flag+"/[a-zA-Z0-9]+");
Matcher m=p.matcher(url);if(m.find()){
str= m.group(0).toLowerCase().split("/")[1];
}returnstr;
}public static voidmain(String[] args) {
String url= "http://cms.yhd.com/sale/vtxqCLCzfto?tc=ad.0.0.17280-32881642.1&tp=1.1.36.9.1.LEffwdz-10-35RcM&ti=ZX8H";
GetCommentNameOrId gs= newGetCommentNameOrId();
System.out.println(gs.evaluate(url,"sale"));
}
}
传参:
url:http://cms.yhd.com/sale/vtxqCLCzfto?tc=ad.0.0.17280-32881642.1&tp=1.1.36.9.1.LEffwdz-10-35RcM&ti=ZX8H
flag:sale
最后得到的结果是 :vtxqCLCzfto
二、UDF操作
1、在rptest库中创建表
create tablerptest.rpt_sale_daily(
huodong string,
pvbigint,
uvbigint) partitioned by (ds string,hour string);
2、打jar包,并上传到制定的路径
add jar /opt/litong/lib/hiveUDF.jar
3、指定属性类,创建function
create temporary function GetCommentNameOrId as 'com.litong.hive.udf.GetCommentNameOrId';
4、添加数据到表rpt_sale_daily中
insert overwrite table rptest.rpt_sale_daily partition (ds='2015-08-28',hour='18')select GetCommentNameOrId(url,"sale") huodong,count(url) pv,count(distinct guid) uv from default.track_log awhere ds='2015-08-28' and hour='18'
group byds,GetCommentNameOrId(url,"sale");insert overwrite table rptest.rpt_sale_daily partition (ds='2015-08-28',hour='19')select GetCommentNameOrId(url,"sale") huodong,count(url) pv,count(distinct guid) uv from default.track_log awhere ds='2015-08-28' and hour='19'
group by ds,GetCommentNameOrId(u
5、检查数据是否插入成功
OK,数据添加成功。