2017-04-19 194 views

回答

1

爲了計算GraphX任意兩個節點之間的最大距離,你可以使用Pregel API

的代碼可以是這樣的:

import org.apache.spark.graphx.{Graph, VertexId} 
import org.apache.spark.graphx.util.GraphGenerators 

// A graph with edge attributes containing distances 
val graph: Graph[Long, Double] = 
    GraphGenerators.logNormalGraph(sc, numVertices = 100).mapEdges(e => e.attr.toDouble) 
val sourceId: VertexId = 42 // The ultimate source 
// Initialize the graph such that all vertices except the root have distance infinity. 
val initialGraph = graph.mapVertices((id, _) => 
    if (id == sourceId) 0.0 else Double.PositiveInfinity) 
val sssp = initialGraph.pregel(Double.PositiveInfinity)(
    (id, dist, newDist) => math.max(dist, newDist), // Vertex Program 
    triplet => { // Send Message 
    if (triplet.srcAttr + triplet.attr < triplet.dstAttr) { 
     Iterator((triplet.dstId, triplet.srcAttr + triplet.attr)) 
    } else { 
     Iterator.empty 
    } 
    }, 
    (a, b) => math.max(a, b) // Merge Message 
) 
println(sssp.vertices.collect.mkString("\n")) 
+1

上面的回答將計算到多個節點從一個源節點的距離目的地。然後我們必須尋找sssp中的目標節點。 但不是這樣做,是否有可能計算從一個源目的地到一個目的地的距離?,直接提供源和目的地,即2作爲源,12作爲目的地。 – Aroon

相關問題