2016-02-05 112 views
0

sMy Cypher查询为多个起始节点查找常见的子节点。每个路径只有它的节点id被提取并返回,每个路径中有数百行。请参阅p1和p2示例(仅显示3行和两个起点)。只需要多个路径上的公共节点 - Neo4j Cypher

Match p1=(n1:node{name:"x" })-[r:sub*]->(i)), p2=(n2:node{name:"y" })-[r:sub*]->(i)) 
RETURN DISTINCT i, extract(a IN nodes(p1)| a.id) as p1, extract(b IN nodes(p2)| b.id) as p2 

----RESULTS---- 

p1=1,4,3 
p1=1,8,3 
p1=1,8,9,3 

p2=6,7,3 
p2=6,5,9,3 
p2=6,7,10,3 

我想要的是在查询过程中相交于密码的路径,这样我就不必这样做了。在PHP中,我将迭代使用:

$result = array_intersect($p1,$p2); 

这将从上面的示例返回9,3,因为它们是所有路径共享的唯一公共节点。有没有办法在Cypher中这样做,以便我没有返回数百行?

谢谢!

回答

0

我相信这会满足您的需求。

这里是正在考虑的数据的图片。 enter image description here

// match the two different paths with the common ending i 
match p1=(n1:Node {name: 1 })-[:SUB*]->(i) 
, p2=(n2:Node {name: 6 })-[:SUB*]->(i) 

// collect both sets of paths for every 
with i, collect(p1) as p1, collect(p2) as p2 

// recombine the nodes of the first path(s) as distinct collections of nodes 
unwind p1 as p 
unwind nodes(p) as n 
with i, p2, collect(distinct n) as p1 

// recombine the nodes of the second path(s) as distinct collections of  
unwind p2 as p 
unwind nodes(p) as n 
with i, p1, collect(distinct n) as p2 

// return the common ending node with the nodes common to each path 
return i, [n in p1 where n in p2 | n.name] as n 

编辑:更新的解决方案,包括第三路径

// match the two different paths with the common ending i 
match p1=(n1:Node {name: 1 })-[:SUB*]->(i) 
, p2=(n2:Node {name: 6 })-[:SUB*]->(i) 
, p3=(n3:Node {name: 4 })-[:SUB*]->(i) 

// collect both sets of paths for every 
with i, collect(p1) as p1, collect(p2) as p2, collect(p3) as p3 

// recombine the nodes of the first path(s) as distinct collections of nodes 
unwind p1 as p 
unwind nodes(p) as n 
with i, p2, p3, collect(distinct n) as p1 

// recombine the nodes of the second path(s) as distinct collections of  
unwind p2 as p 
unwind nodes(p) as n 
with i, p1, p3, collect(distinct n) as p2 

// recombine the nodes of the third path(s) as distinct collections of  
unwind p3 as p 
unwind nodes(p) as n 
with i, p1, p2, collect(distinct n) as p3 

// return the common ending node with the nodes common to each path 
return i, [n in p1 where n in p2 and n in p3 | n.name] as n 
+0

谢谢,这似乎工作。我无法改变回车线以接受两条以上的路线,例如p3 p4等。我怎样才能结合两个以上?谢谢! – Damon

+0

我添加了3路径解决方案。如果我有一些时间,我会看看我是否可以推出一个通用的* n *路径解决方案。 –

+0

非常感谢这个戴夫 - 你让它看起来很简单! – Damon

相关问题