下面的语句在Neo4j中创建了一个代表性数据集。
我想返回给定输入节点集的最小关系图。
例如,节点集的最小关系图" C"," G"," D"是" C,G,D&#34 ;;并且对于" A"," E"它是" A,G,E"。特定节点的数量是任意的,但要求返回的范围最小。
如何编写此查询?
CREATE (A:Table {name:'A'})
CREATE (B:Table {name:'B'})
CREATE (C:Table {name:'C'})
CREATE (D:Table {name:'D'})
CREATE (E:Table {name:'E'})
CREATE (F:Table {name:'F'})
CREATE (G:Table {name:'G'})
CREATE
(F)-[:Link]->(A),
(A)-[:Link]->(G),
(G)-[:Link]->(E),
(G)-[:Link]->(C),
(G)-[:Link]->(D),
(E)-[:Link]->(B),
(C)-[:Link]->(E)
答案 0 :(得分:1)
这是一个简单的解决方案。生成集合中每对节点之间的最短路径的完整列表。然后将结果路径减少到不同的节点集。
// set up the input nodes as a collection of attribute values to be matched
WITH ['C','G','D'] as inputs
// build a list of pairs that are not the same
UNWIND RANGE(0,size(inputs)-1) as i
UNWIND RANGE(0,size(inputs)-1) as j
WITH CASE
WHEN i > j THEN [inputs[i],inputs[j]]
ELSE null
END as pair
// find all of the shortest paths for each pair
MATCH p=allShortestPaths((a:Table {name: pair[0]})-[:Link*]-(b:Table {name: pair[1]}))
WITH p
// recollect the distinct nodes from the shortest paths
UNWIND nodes(p) as n
RETURN COLLECT(DISTINCT n) as min_relational_scope