cancel
Showing results for 
Search instead for 
Did you mean: 

Head's Up! These forums are read-only. All users and content have migrated. Please join us at community.neo4j.com.

How to get only the closest neighbor in the pattern -[:rel * 0..i]->?

a1olegs
Node Clone

graph:
(:Start)-[:rel]->(:A{comment:'Target'})-[:rel]->(:Some)-[:rel]->(:A{comment:'Fake'})
*no Trees, only one dimension path

query:
MATCH p=(:Start)-[:rel*0..5]->(:A))

I need only the first node labeled "A"
(with the shortest path, and the rest are not needed).
And give it the label "first"

I tried to use
WITH min(length(p)) as pathLength
but labels were assigned to all nodes A

1 ACCEPTED SOLUTION

If it's only a 1-dimensional path, and if there is only a single :Start node, you an use a LIMIT 1 to get the first :A node in that single path:

MATCH p=(:Start)-[:rel*0..5]->(a:A)
WITH a 
LIMIT 1
SET a:First

If you have multiple :Start nodes then you need a different approach (since LIMIT is across all rows, and not per starting row) so you would need to order the paths with respect to the start node:

MATCH p=(s:Start)-[:rel*0..5]->(a:A)
WITH s, a
ORDER BY length(p) ASC
WITH s, head(collect(a)) as first
SET first:First

There are some upcoming APOC aggregation functions that will more efficiently find the first or last element associated with an ordering. I'll update with how to do this once the next APOC release drops.

View solution in original post

1 REPLY 1

If it's only a 1-dimensional path, and if there is only a single :Start node, you an use a LIMIT 1 to get the first :A node in that single path:

MATCH p=(:Start)-[:rel*0..5]->(a:A)
WITH a 
LIMIT 1
SET a:First

If you have multiple :Start nodes then you need a different approach (since LIMIT is across all rows, and not per starting row) so you would need to order the paths with respect to the start node:

MATCH p=(s:Start)-[:rel*0..5]->(a:A)
WITH s, a
ORDER BY length(p) ASC
WITH s, head(collect(a)) as first
SET first:First

There are some upcoming APOC aggregation functions that will more efficiently find the first or last element associated with an ordering. I'll update with how to do this once the next APOC release drops.