我最近不得不从使用Cypher更改为Gremlin,并且我试图转换一个查询,该查询允许用户“删除”一个节点以及所有受此影响的子图节点。它实际上并没有删除节点,只是在受影响的节点上添加了“ DELETED”标签。
我可以使用以下方法在Gremlin中获得一个子图:
g.V(nodeId).repeat(__.inE('memberOf').subgraph('subGraph').outV()).cap('subGraph')
但这不考虑子图中的任何节点,这些节点可能有一条回溯经过原始“已删除”节点的路由,因此不应孤立。
如果采用上述图表; B是要删除的节点。它的子图将包括D,E,G和H。但是,由于E仍然有一条通过C返回A的路线,因此我们不想“删除”它。 D,G和H将没有返回A的路线,因此也应删除。
我的Cypher查询工作如下(在C#中使用Neo4jClient.Cypher):
// Find the node to be deleted i.e. B
.Match("(b {Id: 'B'})")
// Set a DELETED label to B
.Set("b:DELETED")
.With("b")
// Find the central node i.e A
.Match("(a {Id: 'A'})")
// Find the subgraph of B ignoring previously deleted nodes
.Call("apoc.path.subgraphAll(b, { relationshipFilter: '<memberOf', labelFilter: '-DELETED'})")
.Yield("nodes AS subgraph1")
// Get each node in subgraph1 as sg1n
.Unwind("subgraph1", "sg1n")
// Check if each sg1n node has a route back to A ignoring DELETED routes
.Call("apoc.path.expandConfig(sg1n, { optional: true, relationshipFilter: 'memberOf>', labelFilter: '-DELETED', blacklistNodes:[b],terminatorNodes:[a]})")
.Yield("path")
// If there is a path then store the nodes as n
.Unwind("CASE WHEN path IS NULL THEN [null] ELSE nodes(path) END", "n")
// Remove the nodes in n from the original subgraph (This should leave the nodes without a route back)
.With("apoc.coll.subtract(subgraph1, collect(n)) AS subgraph2")
// Set the DELETED label on the remaining nodes
.ForEach("(n IN(subgraph2) | SET n:DELETED)")
我可以通过Gremlin获得类似功能吗?
感谢sel-fish在此问题和this one中的帮助,现在我可以使用:
g.V(itemId) // Find the item to delete.
.union( // Start a union to return
g.V(itemId), // both the item
g.V(itemId) // and its descendants.
.repeat(__.inE('memberOf').outV().store('x')) // Find all of its descendants.
.cap('x').unfold() // Unfold them.
.where(repeat(out('memberOf') // Check each descendant
.where(hasId(neq(itemId))).simplePath()) // to see if it has a path back that doesn't go through the original vertex
.until(hasId(centralId))) // that ends at the central vertex .
.aggregate('exception') // Aggregate these together.
.cap('x').unfold() // Get all the descendants again.
.where(without('exception'))) // Remove the exceptions.
.property('deleted', true) // Set the deleted property.
.valueMap(true) // Return the results.
答案 0 :(得分:1)
首先,将子图中的顶点另存为candidates
:
candidates = g.V().has('Id', 'B').repeat(__.inE('memberOf').subgraph('subGraph').outV()).cap('subGraph').next().traversal().V().toList()
然后,过滤candidates
,保留那些未无法获得不包含Vertex('B')的Vertex('A')路径的对象:
g.V(candidates).where(repeat(out('memberOf').where(has('Id', neq('B'))).simplePath()).until(has('Id','A'))).has('Id', neq('B')).aggregate('expection').V(candidates).where(without('expection'))