Spark - Scala计算

时间:2017-04-23 17:35:15

标签: scala apache-spark

我想使用spark和scala为csv文件中的研究人员(https://en.wikipedia.org/wiki/H-index)计算h-ndex,其格式为

R1:B,R1:A,R1:B,R2:C,R2:B,R2:A,R1:D,R1:B,R1:D,R2:B,R1:A,R1:B

h-index是研究人员的学术指标,它是通过为所有重新定位者创建一个sinlge列表来计算的,并且他们的出版物已经排序 例如R1:{A:10,B:5,C:1}然后找到一个值大于其索引的最后位置的索引(这里是位置2,因为1 <3)。

我找不到使用scala的spark解决方案。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

如果您有这样的文件:

R1:B, R1:A, R1:B, R2:C, R2:B, R2:A, R1:D, R1:B, R1:D, R2:B, R1:A, R1:B
R1:B, R1:A, R1:B, R2:C, R2:B, R2:A, R1:D, R1:B, R1:D, R2:B, R1:A, R1:B
R1:B, R1:A, R1:B, R2:C, R2:B, R2:A, R1:D, R1:B, R1:D, R2:B, R1:A, R1:B

以下是一些想法:

// add a count field to each researcher:paper pair
input.flatMap(line => line.split(", ").map(_ -> 1)).
      // count with research:paper as the key
      reduceByKey(_+_).map{ case (ra, count) => {
          // split research:paper
          val Array(author, article) = ra.split(":")
          // map so that the researcher will be new key
          author -> (article, count)
     // group result by the researcher
     }}.groupByKey.collect

// res15: Array[(String, Iterable[(String, Int)])] = Array((R2,CompactBuffer((B,6), (A,3), (C,3))), (R1,CompactBuffer((A,6), (B,12), (D,6))))