词频统计作为MapReduce入门的一个基础算法,相当与各种语言的“Hello World”程序。下面简单说一下MapReduce的算法实现。
Mapper代码:
public class WordMapper extends Mapper<Object,Text,Text,IntWritable>{
private IntWritable one = new IntWritable(1);
private Text word = new Text();
private String patter = "[^a-zA-Z0-9]";
@Override
protected void map(Object key, Text value, Context context) throws IOException, InterruptedException {
//将非数字、英文的字符转换为空格
StringTokenizer str = new StringTokenizer(value.toString().replaceAll(patter," ").toLowerCase());
while(str.hasMoreTokens()){
word.set(str.nextToken());
context.write(word,one);
}
}
}
一个文本文件被程序读取时,Mapper默认的LineRecordReader得到的value值是文本文件的一行,key值为初始偏移量。假如一个文本内容为:
Hello World! Line one.
Hello World! Line two.
则第一次map获取到的value为:
Hello World! Line one.
Key为0。之后在map中通过循环,将单词一个个提取出来,通过context.write()方法输出为如<word,1>的键值对输出。此时输出的结果为:
<hello,1>,<world,1>,<line,1>,<one,1>
在节点的mapper处理完毕后,处理结果由Reducer处理(中间可以添加combiner、排序等此处暂时省略)。
Reducer代码:
public class WordReducer extends Reducer<Text,IntWritable,Text,IntWritable>{
private IntWritable result = new IntWritable();
@Override
protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
int sum = 0;
for(IntWritable val:values){
sum += val.get();
}
result.set(sum);
context.write(key,result);
}
}
Reducer将相同的key(并非一定相同,可以通过制定不同的算法使不同的值)分配到同一个reducer上。此时可以通过取出value的值进行相加,获得该单词的频率。最后通过context.write函数将结果输出为文本。
Main方法:
public class WordCountTest {
public static void main(String[] args) throws IOException {
Configuration conf=new Configuration();
conf.set("fs.defaultFS", "hdfs://localhost:9000");
conf.set("fs.hdfs.impl", "org.apache.hadoop.hdfs.DistributedFileSystem");
Job job=null;
try{
job=Job.getInstance(conf,"WordCount");
job.setJarByClass(WordCountTest.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
job.setMapperClass(WordMapper.class);
job.setReducerClass(WordReducer.class);
FileInputFormat.addInputPath(job,new Path(args[0]));
FileOutputFormat.setOutputPath(job,new Path(args[1]));
//job.setOutputFormatClass(SequenceFileOutputFormat.class);
job.waitForCompletion(true);
}
catch (Exception e){
e.printStackTrace();
}
}
}
注:Mapper和Reducer泛型声明的几个类型分别为:输入key类型、输入vlaue类型、输出key类型、输出value类型。