[英]Neo4j Cypher: Get neighbours for variable length path given condition, skip those that do not meet condition
我正在研究一個問題,因此將其抽象如下:
(a)-[:PREVIOUS]->(b)-[:PREVIOUS]->(c)-[:PREVIOUS]->(d)-[:PREVIOUS]->(e)-[:PREVIOUS]->(f)
(b)-[:IS]->(:Colour {Name: 'Red'})
(c)-[:IS]->(:Colour {Name: 'Red'})
(d)-[:IS]->(:Colour {Name: 'Red'})
(e)-[:IS]->(:Colour {Name: 'Blue'})
(f)-[:IS]->(:Colour {Name: 'Red'})
注意,
(:Colour {Name: 'Red'})
是唯一的,並且連接到許多節點,例如
(a)-[:IS]->(:Colour {Name: Red})<-[:IS]-(b)
但只有
(e)-[:IS]->(:Colour {Name: Blue})
我正在嘗試構造一個與數據相關的查詢,如上圖所示。 我想做的是獲取一個節點及其2個先前的鄰居。 但是,有一些條件:
我對此進行了嘗試,但無法產生以下輸出。 上圖的COMPLETE輸出應如下所示:
a, b, c
b, c, d
c, d, f
d, f
e
f
注意,對於節點(c),我們返回(d),(f)並跳過(e),因為它是藍色; (d)應該有類似的行為。 (e)僅返回自身,因為它是唯一的藍色節點。 有誰知道是否有一個簡單的解決方案?
假設每個當前未標記的節點都有一個可用於查詢的標簽(我將在此處使用:Node),則此方法應該有效:
// for each node, get its color
MATCH (n:Node)-[:IS]->(myColor)
// find paths to all previous nodes (where the colors match)
// this includes the starting node, which has distance 0
MATCH path = (n)-[:PREVIOUS*0..]->(prev)
WHERE (prev)-[:IS]->(myColor)
// for each node, order its previous nodes by distance
WITH n, prev
ORDER BY length(path) ASC
// grab first three closest (first will always be the node itself)
WITH n, collect(prev)[..3] as prevs
RETURN prevs
ORDER BY size(prevs) DESC
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.