how to get the last node in path in neo4j?

佐手、 提交于 2019-12-04 02:38:54

This would give two arrays. The first array is the last item in each path, the second is each path:

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

Since a path is a collection you can apply the LAST function.

This example is for getting the last node from every branch of nodes
connected with a next_action relations

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

there is something a little strange, running this query in the Neo4j GUI interface will bring all the last nodes. Running the same query from py2neu will not. When running from py2neo the following modification will work

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!