在 Neo4j 中到达第一个需要的节点时停止遍历

Stop traversing when the first required node is reached in Neo4j

抱歉,如果问题看起来含糊不清 :) 我正在寻找的查询有点具体。考虑图中的以下分支:

( a:Detector {prop_x:假})-->( b:Category {prop_x:假})-->( c:Category { prop_x:True})-->( d:Category {prop_x:True})-->(...) 等等

现在我想获取a的所有父节点,直到到达一个节点,其中一个节点的属性 prop_x为True,然后停止。即我想要路径:

( a:Detector {prop_x:假})-->( b:Category {prop_x:假})-->( c:Category { prop_x:正确})

我尝试了以下查询:

match path=(child:Detector)-[*]->(parent:Category {prop_x:True}) return path

但我得到的路径还包括节点 (d:Category),因为它也有 prop_x True.

我想要图中所有这样的路径,从 Detector 节点开始,直到第一个 "parent" Category 节点 prop_x True

那里的表达式将匹配所有以带有标签 Label 的节点开始并以带有标签 Label 的节点结束并且 prop_xtrue。我假设您知道要从哪里开始,并从 name of A 的节点开始。然后匹配所有以 prop_x of true 结尾的路径。这也可能包括它去 true - false - true 的路径。我按路径长度对生成的路径进行升序排序,并只保留顶部匹配项。

match path=(child:Node {name: 'A'})-[*]->(parent:Node {prop_x:True})
return length(path), nodes(path)
order by length(path)
limit 1

下方新增

每个更新问题的更新,"How to find all such paths from all Detector Nodes?"

我想了一会儿,这就是我想出的...

// first match all of your detector nodes
match (d:Detector)
with d
// then for each detector node match the paths that end with True
match path=d-[*]->(parent:Category {prop_x:True})
// for each detector collect the length and matching nodes
with d, [ length(path), nodes(path) ] as path_match
// order by the detector name and path length so they are grouped and sorted
order by d.name, length(path)
// then collect all of the length, path collections so there is one
// row per detector
with d, collect(path_match) as path_matches
// then return the first Detector and the first (i.e. shortest) collection in the collection of paths
return d.name, path_matches[0]