首页 > 解决方案 > 为什么hadoop对reducer的输入进行排序?

问题描述

对于字数问题,我比较了以下两个 reducer 的时间性能。这些 reducer 的不同之处在于它们是否利用按键排序的输入。

Reducer 1(不使用被排序的输入):

#!/usr/bin/python
import sys

# maps words to their counts
word2count = {}

for line in sys.stdin:
    w = line.strip().split()[0] # this is the word
    word2count[w] = (word2count[w] + 1 if word2count.has_key(w) 
                     else 1)

# Write (unsorted) tuples to stdout
for word in word2count.keys():
    print '%s\t%s' % (word, word2count[word])

Reducer 2(利用被排序的输入):

#!/usr/bin/python
import sys

# maps words to their counts
word2count = {}
last = ""
count = 0

for line in sys.stdin:
    w = line.strip().split()[0] # this is the word
    if w != last and count != 0:
        word2count[last] = count
        last = w
        count = 1
    else: count += 1
if last != "": word2count[last] = count

# Write (unsorted) tuples to stdout
for word in word2count.keys():
    print '%s\t%s' % (word, word2count[word])

两个 reducer 都使用了相同的映射器:

#!/usr/bin/python
import sys
import string

#--- get all lines from stdin ---
for line in sys.stdin:
    #--- to lower case and remove punctuation ---
    line = line.lower().translate(None, string.punctuation)

    #--- split the line into words ---
    words = line.split()

    #--- output tuples [word, 1] in tab-delimited format---
    for word in words: 
        print '%s\t%s' % (word, "1")

我使用“战争与和平”的英文翻译作为输入。reducer 的时间性能(CPU 时间)差异约为 20%。

这是我用来测量时间的命令行:

./mapper.py < war_and_peace.txt | sort | time ./reducer.py > /dev/null

鉴于第一个 reducer 要简单得多,并且对 reducer 的输入进行排序需要时间(这可能会占用这 20%),我的问题是:为什么 hadoop 对reducers 的输入进行排序?是否存在被排序的减速器的输入比字数更重要的问题?(请注意:我意识到需要对每个映射器的输出进行排序以平衡减速器的负载。我的问题是关于合并来自不同映射器的键值对而不是简单地附加它们的动机。 )

标签: hadoopmapreduce

解决方案


这是我认为正确的答案(除非将这个问题标记为重复的人可以在他们找到的帖子中指出我的这个答案,否则他们应该感到羞耻)。这个问题忽略了记忆方面。将键存储在字典中假设所有键都可以放入内存中,但通常情况可能并非如此。按键对减速器的输出进行排序允许一次只使用一个键。


推荐阅读