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

*no Trees, only one dimension path

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

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)
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.

1 Like