[英]Inherit property of parent node for current node in cypher - neo4j
I have run into a problem where I have my graph constructed something like this : 我遇到了一个问题,在此情况下我的图形构造如下:
A
/ \
B C
/ \ / \
D E F G
All my nodes are of type Object:ie, Match (n:Object) And I have created this graph with only one relation (parent and child) ie, (A)-[:child]->(B)
, (A)-[:child]->(C)
, (B)-[r:child]->D
, etc till node G 我所有的节点都是Object:ie,Match(n:Object)类型的,并且我创建的图只有一个关系(父子关系),即
(A)-[:child]->(B)
, (A)-[:child]->(C)
, (B)-[r:child]->D
等,直到节点G
I have a property defined at each node called: levelID
Some of the nodes might not have this levelID. 我在每个节点上定义了一个属性,该属性称为:
levelID
一些节点可能没有此levelID。 The nodes which do not have levelID should inherit that from its parent node. 没有levelID的节点应从其父节点继承该ID。
Now, when I run the cypher (assuming C and G does not have levelID) : 现在,当我运行密码时(假设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
This is not giving the desired output. 这没有提供所需的输出。
Expected: (consider C and G has levelId= null) 预期:(考虑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
But, this is my actual :( 但是,这是我的实际:(
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 node, take path from root to node, and find in this path the first node with the desired property: 查找根节点,采取从根到节点的路径,然后在此路径中找到具有所需属性的第一个节点:
// 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.