首页 文章

在cypher - neo4j中为当前节点的父节点的继承属性

提问于
浏览
0

我遇到了一个问题,我的图形构造如下:

A
        /   \
       B     C
     /  \   /  \
    D    E  F   G

我的所有节点都是Object类型:即Match(n:Object)我创建的这个图只有一个关系(父和子),即 (A)-[:child]->(B)(A)-[:child]->(C)(B)-[r:child]->D 等,直到节点G

我在每个节点上定义了一个属性: levelID 某些节点可能没有此levelID . 没有levelID的节点应该从其父节点继承该节点 .

现在,当我运行cypher时(假设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

1 回答

  • 2

    查找根节点,从根到节点获取路径,并在此路径中查找具有所需属性的第一个节点:

    // 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
    

相关问题