【问题标题】:MRJob sort reducer outputMRJob 排序减速器输出
【发布时间】:2018-12-10 14:42:11
【问题描述】:

有没有办法使用mrjob对reducer函数的输出进行排序?

我认为 reducer 函数的输入是按键排序的,我尝试利用此功能使用另一个 reducer 对输出进行排序,如下所示,我知道值具有数值,我想计算每个键的数量并排序根据此计数的键:

def mapper_1(self, key, line):
    key = #extract key from the line
    yield (key, 1)

def reducer_1(self, key, values):
    yield key, sum(values)

def mapper_2(self, key, count):
    yield ('%020d' % int(count), key)

def reducer_2(self, count, keys):
    for key in keys:
        yield key, int(count)

但它的输出没有正确排序!我怀疑这种奇怪的行为是由于将ints 操作为string 并尝试将其格式化为this link 所说但它没有用!

重要提示:当我使用调试器查看reducer_2 的输出顺序时,顺序是正确的,但作为输出打印出来的却是另外一回事!!!

重要提示 2:在另一台计算机上,相同数据的相同程序返回按预期排序的输出!

【问题讨论】:

    标签: python sorting mapreduce mrjob


    【解决方案1】:

    您可以在第二个 reducer 中将值排序为整数,然后将它们转换为零填充表示:

    import re
    
    from mrjob.job import MRJob
    from mrjob.step import MRStep
    
    WORD_RE = re.compile(r"[\w']+")
    
    
    class MRWordFrequencyCount(MRJob):
    
        def steps(self):
            return [
                MRStep(
                    mapper=self.mapper_extract_words, combiner=self.combine_word_counts,
                    reducer=self.reducer_sum_word_counts
                ),
                MRStep(
                    reducer=self.reduce_sort_counts
                )
            ]
    
        def mapper_extract_words(self, _, line):
            for word in WORD_RE.findall(line):
                yield word.lower(), 1
    
        def combine_word_counts(self, word, counts):
            yield word, sum(counts)
    
        def reducer_sum_word_counts(self, key, values):
            yield None, (sum(values), key)
    
        def reduce_sort_counts(self, _, word_counts):
            for count, key in sorted(word_counts, reverse=True):
                yield ('%020d' % int(count), key)
    

    嗯,这是在内存中对输出进行排序,这可能是一个问题,具体取决于输入的大小。但是你希望它被排序,所以它必须以某种方式排序。

    【讨论】:

    • 谢谢,成功了!但是剩下一点,为什么我的代码在不同的机器上产生不同的输出!我的代码对除我之外的所有计算机上的输出进行了排序!!!
    • 操作系统有哪些?MRJob、python等的版本?
    • 我正在使用 MacOs 和 python 3.5 和 mrjob 0.6.6。它是使用 anaconda 在多个窗口上排序的,我不知道它的版本!
    • 还有其他正在分类的机器? :)
    • 我有 ubuntu 16、python 3.6.2 和 mrjob 0.6.6,但它不适合我。对您链接的 mrjob 问题有评论,建议它应该在组合步骤之后排序,但仅适用于小输入,无论是什么小手段。
    猜你喜欢
    • 2018-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-10
    • 2015-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多