hadoop官方mapreduce简单例子-WordMean

上一篇写了MapReduce的经典例子–WordCount,为了进一步理解和熟悉一下MapReduce这个框架,这次再来看看官方给出的另外一个例子:WordMean

WordMean,Mean我们都知道,是平均数的意思。所以很显然,这个程序是用来统计单词的平均字符数的。

先来跑一下。

在《centos+虚拟机配置hadoop2.5.2-mapreduce-wordcount例子》里面,我已经在hdfs里面新建了一个input文件夹,并且在里面放置了一个test.txt,内容如下:

test.txt的内容
事实上,无论是WordCount还是WordMean,都不仅仅是只处理一个文件,为了验证这一点,我在跑WordMean之前,建多一个文件。

先在linux下新建一个test2.txt

vim /home/txt/test2.txt

内容如下:
test2.txt的内容

将其复制到hdfs下的input文件夹内:

hadoop fs -put /home/txt/text2.txt input

准备工作完毕,现在跑一下程序。仍然是这个jar文件:/hadoop/share/hadoop/mapreduce/sources/hadoop-mapreduce-examples-2.5.2-sources.jar

输出我们放在名为wordmean-output的文件夹下(命令行的最后一个参数),具体运行命令如下:

hadoop jar share/hadoop/mapreduce/sources/hadoop-mapreduce-examples-2.5.2-sources.jar org.apache.hadoop.examples.WordMean input wordmean-output

运行过程中,控制台最后几行信息输出如下:

Bytes Read=173
File Output Format Counters
Bytes Written=20
The mean is: 5.653846153846154

最后一行显示,the mean is 5.653846153846154,即单词的平均字符数。

我手工统计了一下,一共有26个单词,合计147个字符,147/26,确实是这个数。为了进一步确认,到wordmean-output那里看一下输出结果。

hadoop fs -cat wordmean-output/part-r-00000

结果如下,看来我手工也没数错哈哈:
WORDMEAN输出结果

跑完程序了,把源代码贴一下:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

import com.google.common.base.Charsets;

public class WordMean extends Configured implements Tool {

  private double mean = 0;

  private final static Text COUNT = new Text("count");
  private final static Text LENGTH = new Text("length");
  private final static LongWritable ONE = new LongWritable(1);

  
  public static class WordMeanMapper extends
      Mapper<Object, Text, Text, LongWritable> {

    private LongWritable wordLen = new LongWritable();

    
    public void map(Object key, Text value, Context context)
        throws IOException, InterruptedException {
      StringTokenizer itr = new StringTokenizer(value.toString());
      while (itr.hasMoreTokens()) {
        String string = itr.nextToken();
        this.wordLen.set(string.length());
        context.write(LENGTH, this.wordLen);
        context.write(COUNT, ONE);
      }
    }
  }


  public static class WordMeanReducer extends
      Reducer<Text, LongWritable, Text, LongWritable> {

    private LongWritable sum = new LongWritable();

    
    public void reduce(Text key, Iterable<LongWritable> values, Context context)
        throws IOException, InterruptedException {

      int theSum = 0;
      for (LongWritable val : values) {
        theSum += val.get();
      }
      sum.set(theSum);
      context.write(key, sum);
    }
  }

  private double readAndCalcMean(Path path, Configuration conf)
      throws IOException {
    FileSystem fs = FileSystem.get(conf);
    Path file = new Path(path, "part-r-00000");

    if (!fs.exists(file))
      throw new IOException("Output not found!");

    BufferedReader br = null;

    // average = total sum / number of elements;
    try {
      br = new BufferedReader(new InputStreamReader(fs.open(file), Charsets.UTF_8));

      long count = 0;
      long length = 0;

      String line;
      while ((line = br.readLine()) != null) {
        StringTokenizer st = new StringTokenizer(line);

        // grab type
        String type = st.nextToken();

        // differentiate
        if (type.equals(COUNT.toString())) {
          String countLit = st.nextToken();
          count = Long.parseLong(countLit);
        } else if (type.equals(LENGTH.toString())) {
          String lengthLit = st.nextToken();
          length = Long.parseLong(lengthLit);
        }
      }

      double theMean = (((double) length) / ((double) count));
      System.out.println("The mean is: " + theMean);
      return theMean;
    } finally {
      if (br != null) {
        br.close();
      }
    }
  }

  public static void main(String[] args) throws Exception {
    ToolRunner.run(new Configuration(), new WordMean(), args);
  }

  @Override
  public int run(String[] args) throws Exception {
    if (args.length != 2) {
      System.err.println("Usage: wordmean <in> <out>");
      return 0;
    }

    Configuration conf = getConf();

    @SuppressWarnings("deprecation")
    Job job = new Job(conf, "word mean");
    job.setJarByClass(WordMean.class);
    job.setMapperClass(WordMeanMapper.class);
    job.setCombinerClass(WordMeanReducer.class);
    job.setReducerClass(WordMeanReducer.class);
    job.setOutputKeyClass(Text.class);
    job.setOutputValueClass(LongWritable.class);
    FileInputFormat.addInputPath(job, new Path(args[0]));
    Path outputpath = new Path(args[1]);
    FileOutputFormat.setOutputPath(job, outputpath);
    boolean result = job.waitForCompletion(true);
    mean = readAndCalcMean(outputpath, conf);

    return (result ? 0 : 1);
  }

  /**
   * Only valuable after run() called.
   * 
   * @return Returns the mean value.
   */
  public double getMean() {
    return mean;
  }
}

 

简单分析一下,大概的过程如下:

map过程

看第43和44行,可以知道map输出了两个键值对,一个是<“length”,单词的长度>,一个是<“count”,1>即单词的个数。

reduce过程

代码56至66行。对已经处理好的键值对进行最终处理,分别处理<“length”,<单词的长度>>,和<“count”,<1,1,1,1,1…>>,做的是同样的处理–累加。

readAndCalcMean方法

第68行到111行,主要是读取输出的文件,计算平均数。如上文所示,文件里面的内容如下:

WORDMEAN输出结果

所以这个方法,就是用来读取26和147两个数字,作除法,然后输出到屏幕。具体代码写的很清楚,就不细读了。

hadoop官方mapreduce简单例子-WordCount代码解读

WordCount经常在我们初学mapreduce的时候,被作为最简单的例子来讲解,这次我们就从官方给出的源码入手,看看是怎么回事。

所谓Mapreduce,就是Map(映射)”和”Reduce(归约)。map过程,就是把一组<key,value>映射成新的<key,value>;reduce过程,就是把map过程产生的一些列<key,value>,其中那些key相同的,归约成<key,<values>>来处理,一个key对应一组value。

有了这点认识,我们来看看hadoop的mapreduce源码范例:wordcount。

这个程序用来统计一个文本里面各个单词出现的个数。具体怎么运行可以参看我之前写的《centos+虚拟机配置hadoop2.5.2-mapreduce-wordcount例子

下面分析一下WordCount源码:

Map过程:

  public static class TokenizerMapper 
       extends Mapper<Object, Text, Text, IntWritable>{
    
    private final static IntWritable one = new IntWritable(1);
    private Text word = new Text();
      
    public void map(Object key, Text value, Context context
                    ) throws IOException, InterruptedException {
      StringTokenizer itr = new StringTokenizer(value.toString());
      while (itr.hasMoreTokens()) {
        word.set(itr.nextToken());
        context.write(word, one);
      }
    }
  }

关于mapper类的要点:

  • maps将输入的键值对输出为中间键值对,输出不一定是和输入是同样类型的,一个输入键值对可以输出多个键值对,也可能不输出。
  • hadoop的Map-Reduce框架对每一个InputSplit键值对都生成一个map任务,这些键值对是由InputFormat生成的。
  • 框架首先调用setup函数,随后是map函数(InputSplit产生的每一个键值对都调用一次),最后调用finally函数。在wordcount中,只重写了map函数。
  • mapper的输出被分成了不同组,供每个reducer来处理,我们可以通过实现抽象类Partitioner来控制排序和分组。

TokenizerMapper类的简单解析:

由于继承mapper类,因此要实现map()方法。
其中有这么一行代码:

StringTokenizer itr = new StringTokenizer(value.toString());

value是传进来的值,对于这个例子而言,是一行的文本,将一行分割成一个又一个单词,然后,用一个while循环迭代,生成新的(key,value)。代码如下:

while (itr.hasMoreTokens()) {
    word.set(itr.nextToken());
    context.write(word, one);
}

其中的one这个变量,是在刚开始声明的:

private final static IntWritable one = new IntWritable(1);

用来计数,这里是1,所以,输出的(key,value)都是这样的形式:(“单词”,1)。可供之后处理。

Reduce过程:

  public static class IntSumReducer 
       extends Reducer<Text,IntWritable,Text,IntWritable> {
    private IntWritable result = new IntWritable();

    public 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类的要点:

  • reducer将中间输出键值对中那些键相同的合并,值为集合。
  • reduce主要有三个阶段:
    1. shuffle洗牌:reducer将排序好的输出从每个mapper里面复制出来,整个过程用HTTP来通信。
    2. sort排序:框架将reducer的具有相同键的输入合并排序,因为不同的mapper可能有相同的键,shuffle过程和sort过程是同时进行的。
    3. Reduce归约:在reduce阶段,每个key传进来,reduce方法都被调用一次,进行归约。

IntSumReducer类的简单解析:

重写了reduce方法,由于之前已经有map过程了,因此此时传进来的键值对的形式是<key,>,即value不是一个值,而是值的集合。用一个for循环,即可遍历某个key里面的所有值:

for (IntWritable val : values) {
    sum += val.get();
}

这个for循环将某个key对应的所有的value累加,即某单词出现次数的累加。
然后把结果输出:

result.set(sum);
context.write(key, result);

其中的result在之前声明了:

private IntWritable result = new IntWritable();

是整型,所以之后context.write(key,result)就把某单词出现的次数输出了。

Mapreduce的整个过程:

  public static void main(String[] args) throws Exception {
    Configuration conf = new Configuration();
    String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
    if (otherArgs.length < 2) {
      System.err.println("Usage: wordcount <in> [<in>...] <out>");
      System.exit(2);
    }
    Job job = new Job(conf, "word count");
    job.setJarByClass(WordCount.class);
    job.setMapperClass(TokenizerMapper.class);
    job.setCombinerClass(IntSumReducer.class);
    job.setReducerClass(IntSumReducer.class);
    job.setOutputKeyClass(Text.class);
    job.setOutputValueClass(IntWritable.class);
    for (int i = 0; i < otherArgs.length - 1; ++i) {
      FileInputFormat.addInputPath(job, new Path(otherArgs[i]));
    }
    FileOutputFormat.setOutputPath(job,
      new Path(otherArgs[otherArgs.length - 1]));
    System.exit(job.waitForCompletion(true) ? 0 : 1);
  }

要点:

  • Configuration conf = new Configuration(); 这句新建了一个配置对象conf,可以配置mapreduce的一些参数,这里没有对配置作过多的调整。
  • Job job = new Job(conf, “word count”); 这句新建了一个job,用于控制整个工作流程,接下来的6个set函数:
    job.setJarByClass(WordCount.class);
    job.setMapperClass(TokenizerMapper.class);
    job.setCombinerClass(IntSumReducer.class);
    job.setReducerClass(IntSumReducer.class);
    job.setOutputKeyClass(Text.class);
    job.setOutputValueClass(IntWritable.class);

它们分别是:
1.设置工作的类名,这里是WordCount
2.设置mapper的类:TokenizerMapper.class)
3.设置combiner的类:IntSumReducer.class
4.设置reducer的类:IntSumReducer.class,和combiner是一样的。
5.设置输出key的格式,text类型
6.设置输出value的格式,int类型。

  • 接着就是设置输入输出路径,都由命令行参数来指定
  • 最后调用job.waitForCompletion(true) 来开始工作。

最后附上完整源代码:

import java.io.IOException;
import java.util.StringTokenizer;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;

public class WordCount {

  public static class TokenizerMapper 
       extends Mapper<Object, Text, Text, IntWritable>{
    
    private final static IntWritable one = new IntWritable(1);
    private Text word = new Text();
      
    public void map(Object key, Text value, Context context
                    ) throws IOException, InterruptedException {
      StringTokenizer itr = new StringTokenizer(value.toString());
      while (itr.hasMoreTokens()) {
        word.set(itr.nextToken());
        context.write(word, one);
      }
    }
  }
  
  public static class IntSumReducer 
       extends Reducer<Text,IntWritable,Text,IntWritable> {
    private IntWritable result = new IntWritable();

    public 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);
    }
  }

  public static void main(String[] args) throws Exception {
    Configuration conf = new Configuration();
    String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
    if (otherArgs.length < 2) {
      System.err.println("Usage: wordcount <in> [<in>...] <out>");
      System.exit(2);
    }
    Job job = new Job(conf, "word count");
    job.setJarByClass(WordCount.class);
    job.setMapperClass(TokenizerMapper.class);
    job.setCombinerClass(IntSumReducer.class);
    job.setReducerClass(IntSumReducer.class);
    job.setOutputKeyClass(Text.class);
    job.setOutputValueClass(IntWritable.class);
    for (int i = 0; i < otherArgs.length - 1; ++i) {
      FileInputFormat.addInputPath(job, new Path(otherArgs[i]));
    }
    FileOutputFormat.setOutputPath(job,
      new Path(otherArgs[otherArgs.length - 1]));
    System.exit(job.waitForCompletion(true) ? 0 : 1);
  }
}