首页 文章

如何检查节点列表遵循neo4j中的有序路径?

提问于
浏览
1

我在neo4j图数据库中有一个存储为链的节点列表,如下所示:

root node1-> neo4j-> graph - > database . root node2-> neo4j-> graph - > search . root node3-> neo4j-> internals .

如果我给出一个节点列表(动态填充)作为输入,例如“neo4j graph database”,我想检查给定的节点序列并返回根文件夹.i.e .

neo4j graph database-> root node1 . neo4j graph - > root node1,root node2 . neo4j - > root node1,root node2,root node3 .


1 回答

  • 0

    首先,这里有一些看起来像你的样本的数据 . 我做了一些假设,列出的数据都是单独的链 .

    create (r1:Root {name: 'Root 1'})
    create (n1:Node {name: 'Neo4j'})
    create (n2:Node {name: 'Graph'})
    create (n3:Node {name: 'Database'})
    create r1-[:CONNECTED]->n1-[:CONNECTED]->n2-[:CONNECTED]->n3
    create (r2:Root {name: 'Root 2'})
    create (n4:Node {name: 'Neo4j'})
    create (n5:Node {name: 'Graph'})
    create (n6:Node {name: 'Search'})
    create r2-[:CONNECTED]->n4-[:CONNECTED]->n5-[:CONNECTED]->n6
    create (r3:Root {name: 'Root 3'})
    create (n7:Node {name: 'Neo4j'})
    create (n8:Node {name: 'Internals'})
    create r3-[:CONNECTED]->n7-[:CONNECTED]->n8
    return *
    

    现在,这是一个适用于有序列表的解决方案 . 0 ..使它能够使用只有一个节点的有序列表 .

    // start with the ordered list of node names
    with ['Neo4j', 'Graph', 'Database'] as ordered_list
    // start by matching paths that begin with the first node
    // in the ordered list and end with the last node
    match p=((a:Node {name: ordered_list[0]})-[:CONNECTED*0..]-(b:Node {name: ordered_list[length(ordered_list)-1]}))
    // collect these as the list of potential candidates
    with collect(p) as candidates, ordered_list
    // pass through the list and only keep the candidates that are 
    // the same length as the ordered list
    unwind candidates as candidate
    with case when (length(nodes(candidate)) = length(ordered_list)) 
      then candidate
    end as candidate, ordered_list
    // recollect the filtered candidates
    with collect(candidate) as candidates, ordered_list
    // pass through the candidates now again and compare the names
    // of the ordered list to the original ordered list
    // only keep those that match as matched
    unwind candidates as candidate
    with case 
      when reduce(names = [], n in nodes(candidate) | names + n.name) = ordered_list 
      then candidate
    end as matched
    // with the matched nodes find the root node that is attached to
    // first node in each matched path
    match (r:Root)--(head:Node)
    where id(head) = id(nodes(matched)[0])
    // return the root and the matched path nodes
    return r.name, nodes(matched)
    

相关问题