[英]Inherit property of parent node for current node in cypher - neo4j
我遇到了一個問題,在此情況下我的圖形構造如下:
A
/ \
B C
/ \ / \
D E F G
我所有的節點都是Object:ie,Match(n:Object)類型的,並且我創建的圖只有一個關系(父子關系),即(A)-[:child]->(B)
, (A)-[:child]->(C)
, (B)-[r:child]->D
等,直到節點G
我在每個節點上定義了一個屬性,該屬性稱為: levelID
一些節點可能沒有此levelID。 沒有levelID的節點應從其父節點繼承該ID。
現在,當我運行密碼時(假設C和G沒有levelID):
MATCH (n1:Object)-[:child]->(n2:Object)
return n2.id as id,
CASE
WHEN n2.levelId is null
THEN n1.levelId //I am stuck here. (what if node C has levelID as null)
ELSE n2.levelId
END AS level
這沒有提供所需的輸出。
預期:(考慮C和G的levelId = null)
id node level
1 A 1
2 B 2
3 C 1
4 D 4
5 E 5
6 F 6
7 G 1
但是,這是我的實際:(
id node level
1 A 1
2 B 2
3 C 1
4 D 4
5 E 5
6 F 6
7 G null
查找根節點,采取從根到節點的路徑,然后在此路徑中找到具有所需屬性的第一個節點:
// Find root
MATCH (root:Object) WHERE NOT (:Object)-[:child]->(root) WITH root
// Loop through nodes
MATCH (n:Object) WITH n, root
// The path from the root to the node
MATCH path = (root)-[:child*0..]->(n)
WITH n,
// An array of properties (including those which are null)
EXTRACT(node IN NODES(path) | node.levelId) AS levelIdsForTest
WITH n,
// Filter the ones that are not null
FILTER(level IN levelIdsForTest WHERE level IS NOT NULL) AS levelIds
RETURN n.id AS id,
n.levelId AS selfId,
// Take the last one - it is the nearest
LAST(levelIds) AS inheritId
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.