10

In this cypher query,the longest path/paths between nodes which have relationship with STATUS="on" property with each other,will be returned,but I want to get also the last node of the path/paths.

query:

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

how should I add it to the query? thanks.

4

4 回答 4

8

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
于 2013-11-04T21:03:28.807 回答
2

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

于 2013-11-04T18:16:19.093 回答
1

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
于 2019-02-07T20:59:43.810 回答
0

As of Neo4J 4.X FILTER() is not longer supported so it can be replaced with REDUCE(). Here's how ::

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
于 2021-06-18T10:08:11.890 回答