找到最小的数字hadoop流式python

时间:2012-10-04 18:46:08

标签: python hadoop mapreduce hadoop-streaming

我是hadoop框架和地图减少抽象的新手。

基本上,我想在一个巨大的文本文件中找到最小的数字(用“,”分隔)

所以,这是我的代码       mapper.py

 #!/usr/bin/env python

 import sys

 # input comes from STDIN (standard input)
 for line in sys.stdin:
 # remove leading and trailing whitespace
 line = line.strip()
 # split the line into words
numbers = line.split(",")
# increase counters
for number in numbers:
    # write the results to STDOUT (standard output);
    # what we output here will be the input for the
    # Reduce step, i.e. the input for reducer.py
    #
    # tab-delimited; the trivial word count is 1
    print '%s\t%s' % (number, 1)

减速器

  #!/usr/bin/env python

from operator import itemgetter
import sys
smallest_number = sys.float_info.max
for line in sys.stdin:
# remove leading and trailing whitespace
     line = line.strip()

# parse the input we got from mapper.py
     number, count = line.split('\t', 1)
     try:
           number = float(number)
     except ValueError:
            continue

     if number < smallest_number:
        smallest_number = number
        print smallest_number <---- i think the error is here... there is no key value thingy

     print smallest_number

我得到的错误:

       12/10/04 12:07:22 ERROR streaming.StreamJob: Job not successful. Error: NA
      12/10/04 12:07:22 INFO streaming.StreamJob: killJob...
          Streaming Command Failed!

1 个答案:

答案 0 :(得分:0)

首先,我希望您注意,除非您只使用一个减速器,否则您的解决方案将无效。实际上,如果你使用多个减速器,那么每个减速器将吐出它收到的最小数量,并且最终会得到多个减速器。但接下来的问题是,如果我只需要使用一个reducer来解决这个问题(即只有一个任务),那么使用MapReduce可以获得什么?这里的诀窍是映射器将并行运行。另一方面,您不希望映射器输出读取的每个数字,否则一个reducer将不得不查看整个数据,这对顺序解决方案没有任何改进。解决此问题的方法是让每个映射器仅输出它读取的最小数字。此外,由于您希望所有映射器输出都转到同一个reducer,因此映射器输出键必须与所有映射器相同。

映射器看起来像这样:

#!/usr/bin/env python                              

import sys

smallest = None
for line in sys.stdin:
  # remove leading and trailing whitespace          
  line = line.strip()
  # split the line into words                       
  numbers = line.split(",")
  s = min([float(x) for x in numbers])
  if smallest == None or s < smallest:
    smallest = s

print '%d\t%f' % (0, smallest)

减速器:

#!/usr/bin/env python                                           

import sys

smallest = None
for line in sys.stdin:
  # remove leading and trailing whitespace                       
  line = line.strip()
  s = float(line.split('\t')[1])
  if smallest == None or s < smallest:
    smallest = s

print smallest

还有其他可能的方法来解决这个问题,例如使用MapReduce框架本身对数字进行排序,以便reducer接收的第一个数字是最小的。如果您想了解更多MapReduce编程范例,可以阅读this tutorial with examples, from my blog