mapreduce wordcount 理解

话说mapreduce学了一段时间,总有一个问题影响到我,其实特别简单,如:wordcount统计个数,在看代码时总是能看懂,但是真正的逻辑反而一直不明比,比如map端时怎么处理,reduce时又是怎么处理的,现在明白了。

原理是这样的,map端时读取每一行数据,并把每行数据中的一个字符统计一次,如下:

map 数据 {key,value} :

    {0,hello word by word}

    {1,hello hadoop by hadoop}

上面就是map端输入的key与value,在map端处理后会生成以下数据:

   {hello,1} {word,1} {by,1} {word,1}

    {hello,1} {hadoop,1} {by,1} {hadoop,1}

当看到这时大家都能明白,但是在reduce端时,就怎么也看不明白了,不知道是怎么对字符做统一的,再下通过对hadoop原理的分析得出在到reduce端时,会对map端发过来的数据进行清洗,清洗后的数据应该是以下结构:

[{hello},{1,1}] [{word},{1,1}] [{by},{1,1}] [{hadoop},{1,1}]

然后输入到reduce端,reduce会对每一个values做循环操作,对数据进行叠加,并输出到本地,具体代码请继续欣赏,不做多过解析。

public class WordCount extends Configured implements Tool{
 public static class Map extends Mapper<LongWritable,Text,Text,IntWritable>{
  private final static IntWritable one = new IntWritable(1);
  private Text word = new Text();
  public void map(LongWritable key,Text value, Context context)
  throws IOException,InterruptedException{
   String line = value.toString();
   StringTokenizer tokenizer = new StringTokenizer();
   while(tokenizer.hasMoreTokens()){
    word.set(tokenizer.nextToken);
    context.write(word,one);
   }
  }
 }
 
 public static class Reduce extends Reducer<Text,IntWritable,Text,IntWritable>{
  public void reduce(Text key,Iterable<IntWritable> values,Context context)
  throws IOException,InterruptedException{
   int sum = 0 ;
   for(IntWritable val: values) {
    sum += val.get();
   }
   context.write(key,new IntWritable(sum));
  }
 }
 
 public int run(String[] arge) throws Exception{
  Job job = new Job(getConf());
  job.setJarByClass(WordCount.class);
  job.setJobName("wordcount");
  
  job.setOutputKeyClass(Text.class);
  job.setOutputValueClass(IntWritable.class);
  
  job.setMapperClass(Map.class);
  job.setReduceClass(reduce.class);
  
  job.setInputFormatClass(TextInputFormat.class);
  job.setOutputFormatClass(TextInputFormat.class);
  
  FileInputFormat.setInputPaths(job,new Path(args[0]));
  FileInputFormat.setOutputPaths(job, new Path(args[1]));
  
  boolean success = job.waitForCompletion(true);
  return success ? 0 : 1;
 }
 
 public static void main(String[] args) throws Exception{
  int ret = ToolRunner.run(new WordCount(),args);
  System.exit(ret);
 }
}
  

    

转载于:https://my.oschina.net/u/1766330/blog/365109

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值