【问题标题】:MapReduce : Can Mapper and Reducer share variable?MapReduce:Mapper 和 Reducer 可以共享变量吗?
【发布时间】:2017-06-14 22:18:50
【问题描述】:

我将JavaHadoop 用于MapReduce

输入(txt 文件):

doc1    apple pizza apple
doc2    pear apple
doc3    cookie noodle apple
doc4    pizza milk
.
.
.

Mapper 读取上述文本文件的每一行并发出 (word, 1) 。但是由于Reducer 应该知道每个单词在整个文档中出现了多少。例如,对于“apple”,它出现在 doc1、doc2、doc3 中,因此在 Reducer 中需要 '3'。

我的想法是这样的: 由于ReducerMapper 的所有工作完成后开始运行,所以Mapper 可以计数每次发出HashMap 时增加HashMap 的值(word, 1)。例如,当Mapper 读取doc1 行时,它将整个内容作为唯一的单词(=> 苹果披萨)。并且每次它发出(word, 1),比如说(apple, 1),做hashMap['apple'] ++

在完成所有Mapper 的工作后,Reducer 访问此HashMap,以便它可以使用每个单词在整个文档中出现的次数。

我已经阅读了How to share a variable in Mapper and Reducer class?,但我想从你们那里得到建议。

p.s 抱歉英语不好,但我不是本地人。如果您看不懂我在说什么,请发表评论。

【问题讨论】:

    标签: java hadoop mapreduce


    【解决方案1】:

    我不确定我是否完全理解你在这里做什么。

    这样做的目的是什么? 如果要计算所有记录中的每个单词有多少次,它将像这样工作:

    映射器:

    function map(){
      String[] arr = line.split(" ");
      foreach(String word : arr){
        context.write(word,1)
      }
    }
    

    映射后,您的所有键将按键排序,并组合在一起。 这是非常重要的功能。

    例子:

     Mapper:
        doc1 will produce:
        apple 1
        pizza 1
        apple 1
    

    在映射器之后,文档将按键分组: 苹果 => [1,1] 披萨 => [1]

    减速机:

    function reduce(apple, [1,1]){
    
            count=0;
            foreach(value in values) do:
              count++
            done
    
            context.write(key,count) ; //Here you will have the number of apples 
        in all your docs 
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-19
      • 2011-06-25
      相关资源
      最近更新 更多