2016-02-05 42 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

相關問題