计算Hadoop上偶数/奇数对的总和?

时间:2013-01-04 20:47:00

标签: scala hadoop functional-programming cascading scalding

我想为Hadoop创建一个并行scanLeft(计算关联运算符的前缀和)函数(特别是scalding;有关如何完成,请参见下文)。

给定hdfs文件中的一系列数字(每行一个),我想用连续偶数/奇数对的总和计算一个新序列。例如:

输入序列:

0,1,2,3,4,5,6,7,8,9,10

输出序列:

0 + 1,2 + 3,4 + 5,6 + 7,8 + 9,10

1,5,9,13,17,10

我认为为了做到这一点,我需要为Hadoop编写一个InputFormat和InputSplits类,但我不知道如何做到这一点。

请参阅本节3.3 here。下面是Scala中的示例算法:

 // for simplicity assume input length is a power of 2

def scanadd(input : IndexedSeq[Int]) : IndexedSeq[Int] =   
if (input.length == 1)
  input 
else { 
//calculate a new collapsed sequence which is the sum of sequential even/odd pairs 
val collapsed = IndexedSeq.tabulate(input.length/2)(i => input(2 * i) + input(2*i+1))

//recursively scan collapsed values
val scancollapse = scanadd(collapse)

//now we can use the scan of the collapsed seq to calculate the full sequence

val output = IndexedSeq.tabulate(input.length)(
i => i.evenOdd match {             

//if an index is even then we can just look into the collapsed sequence and get the value
// otherwise we can look just before it and add the value at the current index

   case Even => scancollapse(i/2) 
   case Odd => scancollapse((i-1)/2) + input(i)  
}

output
}

我知道这可能需要进行一些优化才能与Hadoop很好地协作。直接翻译这个我认为会导致效率非常低的Hadoop代码。例如,显然在Hadoop中你不能使用IndexedSeq。我很感激你看到的任何具体问题。不过,我认为它可能会很好地运作。

2 个答案:

答案 0 :(得分:0)

多余的。你的意思是这段代码吗?

val vv = (0 to 1000000).grouped(2).toVector
vv.par.foldLeft((0L, 0L, false))((a, v) => 
    if (a._3) (a._1, a._2 + v.sum, !a._3) else (a._1 + v.sum, a._2, !a._3))

答案 1 :(得分:0)

This是我找到的用于编写InputFormat和RecordReader的最佳教程。我最终将整个拆分作为一个ArrayWritable记录读取。