Word Count Example of Hadoop V1.0 – Mapper的实现

本文继续来看Mapper的实现。

Mapper

01 public static class Map
02         extends Mapper<LongWritable, Text, Text, IntWritable> {
03     private final static IntWritable one = new IntWritable(1);
04     private Text word = new Text();
05 
06     public void map(LongWritable key, Text value, Context context)
07             throws IOException, InterruptedException {
08         String line = value.toString();
09         StringTokenizer tokenizer = new StringTokenizer(line);
10         while (tokenizer.hasMoreTokens()) {
11             word.set(tokenizer.nextToken());
12             context.write(word, one);
13         }
14     }
15 }

我们实现了Driver中指定的Map.class,这个类继承自Mapper<LongWritable, Text, Text, IntWritable>,其中四个类型以此是input的key和value,和Mapper输出的Key和Value。

03     private final static IntWritable one = new IntWritable(1);
04     private Text word = new Text();

这两行是定义mapper的输出,看类型就能看出来,Text是mapper输出的key,IntWritable是mapper输出的value。

06     public void map(LongWritable key, Text value, Context context)

继承Mapper就要实现map函数,LongWritable和Text即mapper的输入,Context是mapper和Hadoop系统交互的工具。它可以存储配置数据,还能输出key-value。

getConfiguration()方法返回一个Configuration,里面包含了Hadoop Job的配置数据。程序员可以在配置数据里加入任意的key-value对(例如:Job.getConfiguration().set(“Key”, “Value”)),当然,也可以把它读出来(Context.getConfiguration().get(“Key”))。这种功能一般会在Mapper的setup()方法里面实现。

map(KeyInType, ValInType, Context)是由Mapper.run()方法调用的。map方法处理数据后,通过Context.write(KeyOutType, ValOutType)方法输出。

在mapper结束后,应用程序可以通过重载Mapper的cleanup()方法来做一些需要的收尾工作。

Mapper的输出对的类型不需要和输入对的类型一致,而且给定一个输入对,可以对应于0个或多个输出对。

Context的另一个作用是report progress,可以像Hadoop Job发送任何应用层的状态信息,或者只是告诉别人自己还活着。

posted @ 2011-11-08 21:56  Jonson Li  阅读(335)  评论(0编辑  收藏  举报