这个问题是关于Spark GraphX的。我想通过删除与某些其他节点相邻的节点来计算子图。
示例
[任务]保留不是C2节点的邻居的节点和B节点。
输入图表:
┌────┐
┌─────│ A │──────┐
│ └────┘ │
v v
┌────┐ ┌────┐ ┌────┐ ┌────┐
│ C1 │────>│ B │ │ B │<────│ C2 │
└────┘ └────┘ └────┘ └────┘
^ ^
│ ┌────┐ │
└─────│ A │──────┘
└────┘
输出图:
┌────┐
┌─────│ A │
│ └────┘
v
┌────┐
│ B │
└────┘
^
│ ┌────┐
└─────│ A │
└────┘
如何优雅地编写返回输出图的GraphX查询?
答案 0 :(得分:3)
这是另一种解决方案。此解决方案使用aggregateMessages将一个整数(1)发送到应从图中删除的B。生成的顶点集与图形连接,随后的子图调用将从输出图中删除不需要的B。
// Step 1: send the message (1) to vertices that should be removed
val deleteMe = graph.aggregateMessages[Int](
ctx => {
if (ctx.dstAttr.equals("B") && ctx.srcAttr.equals("C")) {
ctx.sendToDst(1) // 1 means delete, but number is not actually used
}
},
(a,b) => a // choose either message, they are all (1)
)
// Step 2: join vertex sets, original and deleteMe
val joined = graph.outerJoinVertices(deleteMe) {
(id, origValue, msgValue ) => msgValue match {
case Some(number) => "deleteme" // vertex received msg
case None => origValue
}
}
// Step 3: Remove nodes with domain = deleteme
joined.subgraph(vpred = (id, data) => data.equals("deleteme"))
我正在考虑一种只使用一个中间删除标记的方法,例如“deleteme”,而不是1和“deleteme”。但这是一个很好的,因为我可以做到这一点。
答案 1 :(得分:2)
使用val nodesAB
GraphOps.collectNeighbors
的另一种方法
val nodesAB = graph.collectNeighbors(EdgeDirection.Either)
.filter{case (vid,ns) => ! ns.map(_._2).contains("C2")}.map(_._1)
.intersection(
graph.vertices
.filter{case (vid,attr) => ! attr.toString.startsWith("C") }.map(_._1)
)
其余的工作方式与您相同:
val solution1 = Graph(nodesAB, graph.edges) .
subgraph(vpred = {case(id, label) => label != null})
如果你想使用可以(?)更具可扩展性的DataFrames,那么首先我们需要将nodesAB转换为DataFrame:
val newNodes = sqlContext.createDataFrame(
nodesAB,
StructType(Array(StructField("newNode", LongType, false)))
)
你用这个创建并边缘化DataFrame:
val edgeDf = sqlContext.createDataFrame(
graph.edges.map{edge => Row(edge.srcId, edge.dstId, edge.attr)},
StructType(Array(
StructField("srcId", LongType, false),
StructField("dstId", LongType, false),
StructField("attr", LongType, false)
))
)
然后你可以这样做来创建没有子图的图形:
val solution1 = Graph(
nodesAB,
edgeDf
.join(newNodes, $"srcId" === $"newNode").select($"srcId", $"dstId", $"attr")
.join(newNodes, $"dstId" === $"newNode")
.rdd.map(row => Edge(row.getLong(0), row.getLong(1), row.getLong(2)))
)
答案 2 :(得分:0)
一种解决方案是使用三元组视图来识别作为C1节点的邻居的B节点的子集。接下来,将那些与A节点联合起来。接下来,创建一个新的图表:
// Step 1
// Compute the subset of B's that are neighbors with C1
val nodesBC1 = graph.triplets .
filter {trip => trip.srcAttr == "C1"} .
map {trip => (trip.dstId, trip.dstAttr)}
// Step 2
// Union the subset B's with all the A's
val nodesAB = nodesBC1 .
union(graph.vertices filter {case (id, label) => label == "A"})
// Step 3
// Create a graph using the subset nodes and all the original edges
// Remove nodes that have null values
val solution1 = Graph(nodesAB, graph.edges) .
subgraph(vpred = {case(id, label) => label != null})
在步骤1中,我通过将三元组视图的dstID和dstAttr映射在一起来重新创建节点RDD(包含B节点)。不确定这对大型图表的效率如何?