需求:我们需要实现自定义函数,来提取dns中的名字和对应的汉字。并将查询信息写入到另一张表
一. 显示需求
- 基础表
1 www.baidu.com
2 www.google.com
3 www.taobao.com - 最终结果
baidu 百度
google 谷歌
taobao 淘宝
二. 首先我们需要用编写IDEA编写两个UDF函数,来得到两个字段的结果。
- 编写实现第一个字段的UDF类有两个函数,
一个是getMatcher()匹配url,
另一个是evaluate()返回提取出的信息。
package com.UDF;
import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.hadoop.io.Text;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class WorkUDF extends UDF{
public Text evaluate(Text input)
{
String string1="www.([\\s\\S]*?).com";
String string2=String.valueOf(input);
return new Text(getMatcher(string1,string2));
}
public static String getMatcher(String regex, String source) {
String result = "";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(source);
while (matcher.find()) {
result = matcher.group(1);
}
return result;
}
}
- 编写实现第二个字段的UDF类,判断信息所属的类型。
package com.UDF;
import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.hadoop.io.Text;
public class Work2UDF extends UDF{
public Text evaluate(Text input)
{
if(String.valueOf(input).equals("baidu"))
{
return new Text("百度");
}
if(String.valueOf(input).equals("google"))
{
return new Text("谷歌");
}
if (String.valueOf(input).equals("taobao"))
{
return new Text("淘宝");
}
return null;
}
}
编码阶段结束。
二. 打包项目
打包:
View->TollWindows->Maven Projects->hive->Lifecycle->package
查看包:
C:\Users\nbplus\IdeaProjects\hive7\target
上传包:
rz
三. 创建url表并导入数据
create table URL(
id int,
url string
)
row format delimited fields terminated by "\t";
load data local inpath "/home/hadoop/data/www" overwrite into table URL
hive> select * from url;
OK
1 www.baidu.com
2 www.google.com
3 www.taobao.com
Time taken: 1.582 seconds, Fetched: 3 row(s)
四.添加自定义函数
hive> add jars /home/hadoop/lib/hive-1.0.jar;
Added [/home/hadoop/lib/hive-1.0.jar] to class path
Added resources: [/home/hadoop/lib/hive-1.0.jar]
hive> create temporary function work
> as 'com.UDF.WorkUDF';
OK
Time taken: 0.124 seconds
hive> create temporary function work2
> as 'com.UDF.Work2UDF';
OK
Time taken: 0.008 seconds
五.创建并写入urlplus表
create table URLplus as select work(url),work2(work(url)) from url
hive> select * from urlplus;
OK
baidu 百度
google 谷歌
taobao 淘宝
Time taken: 1.922 seconds, Fetched: 3 row(s)