让我们从下游处理所需的一些导入和变量开始:
import org.apache.spark._
import org.apache.spark.graphx._
import org.apache.spark.rdd.RDD
import scala.util.Random
import org.apache.spark.HashPartitioner
val nPartitions: Integer = ???
val n: Long = ???
val p: Double = ???
接下来,我们需要一个种子 ID 的 RDD,可用于生成边。处理这个问题的一种天真的方法就是这样:
sc.parallelize(0L to n)
由于生成的边数取决于节点 ID,这种方法会产生高度倾斜的负载。我们可以通过重新分区做得更好:
sc.parallelize(0L to n)
.map((_, None))
.partitionBy(new HashPartitioner(nPartitions))
.keys
但更好的方法是从空 RDD 开始并在适当位置生成 id。我们需要一个小帮手:
def genNodeIds(nPartitions: Int, n: Long)(i: Int) = {
(0L until n).filter(_ % nPartitions == i).toIterator
}
可以按如下方式使用:
val empty = sc.parallelize(Seq.empty[Int], nPartitions)
val ids = empty.mapPartitionsWithIndex((i, _) => genNodeIds(nPartitions, n)(i))
只是一个快速的健全性检查(它非常昂贵,所以不要在生产中使用它):
require(ids.distinct.count == n)
我们可以使用另一个助手生成实际的边缘:
def genEdgesForId(p: Double, n: Long, random: Random)(i: Long) = {
(i + 1 until n).filter(_ => random.nextDouble < p).map(j => Edge(i, j, ()))
}
def genEdgesForPartition(iter: Iterator[Long]) = {
// It could be an overkill but better safe than sorry
// Depending on your requirement it could worth to
// consider using commons-math
// https://commons.apache.org/proper/commons-math/userguide/random.html
val random = new Random(new java.security.SecureRandom())
iter.flatMap(genEdgesForId(p, n, random))
}
val edges = ids.mapPartitions(genEdgesForPartition)
最后我们可以创建一个图表:
val graph = Graph.fromEdges(edges, ())