在此cypher查询中,将返回与STATUS =“on”属性相互关联的节点之间的最长路径/路径,但我还想获得路径/路径的最后一个节点。
查询:
START n=node(*)
MATCH p=n-[rels:INCLUDE*]->m
WHERE ALL (rel IN rels
WHERE rel.status='on')
WITH COLLECT(p) AS paths, MAX(length(p)) AS maxLength
RETURN FILTER(path IN paths
WHERE length(path)= maxLength) AS longestPaths
我该如何将其添加到查询中? 感谢。
答案 0 :(得分:7)
这会产生两个数组。第一个数组是每个路径中的最后一个项目,第二个是每个路径:
START n=node(*)
MATCH p=n-[rels:INCLUDE*]->m
WHERE ALL (rel IN rels
WHERE rel.status='on')
WITH COLLECT(p) AS paths, MAX(length(p)) AS maxLength
WITH FILTER(path IN paths WHERE length(path)= maxLength) AS longestPaths
RETURN EXTRACT(path IN longestPaths | LAST(path)) as last, longestPaths
答案 1 :(得分:2)
由于路径是集合,您可以应用LAST
函数。
答案 2 :(得分:1)
此示例用于从节点的每个分支中获取最后一个节点
与next_action
关系
MATCH p=(a:acct)-[:next_action*]->(c)
WITH COLLECT({node:c, l:length(p)}) AS paths, MAX(length(p)) AS maxLength, a.uid as uid
WITH [x IN paths WHERE x.l= maxLength] AS last_node
RETURN last_node
有些奇怪,在Neo4j GUI界面中运行此查询将带走所有最后的节点。从py2neu运行相同的查询不会。 从py2neo运行时,以下修改将起作用
MATCH p=(a:acct)-[:next_action*]->(c)
WITH COLLECT({node:c, l:length(p)}) AS paths, MAX(length(p)) AS maxLength, a.uid as uid
WITH [x IN paths WHERE x.l= maxLength] AS last_node
WITH COLLECT(last_node) as last_nodes
RETURN last_nodes
答案 3 :(得分:0)
从 Neo4J 4.X 开始,不再支持 FILTER(),因此可以将其替换为 REDUCE()。 方法如下::
START n=node(*)
MATCH p=n-[rels:INCLUDE*]->m
WHERE ALL (rel IN rels
WHERE rel.status='on')
WITH COLLECT(p) AS paths, MAX(length(p)) AS maxLength
// WITH FILTER(path IN paths WHERE length(path)= maxLength) AS longestPaths
WITH REDUCE( newPaths = [], path in paths |
CASE
WHEN length(path)= maxLength THEN newPaths + [path]
END ) AS longestPaths
RETURN EXTRACT(path IN longestPaths | LAST(path)) as last, longestPaths