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.

Get top/bottom node by property value

dbeaumon
Node Link

I suspect that I'm just asking a basic question in a new and less intelligent way, but is there a way of getting just the top/bottom node by value without going through an ORDER BY, collect()[..1], UNWIND? It just feels very long-winded, and something that is in some APOC procedure that I don't know about.

With something like this:

(a:SomeNode)-[:SOME_LINK]->(b:OtherNodes)

I would like to walk out of this somehow with a stream of (for example) a, "the b with the latest date in field x".

I hope that question made sense. I am pretty sure I can (and probably should for the practice) do it myself in APOC, but it seems like a pattern that has probably been explored a million times before.

Thanks,

Dave

1 ACCEPTED SOLUTION

You'll need to use ORDER BY in any case, as ordering isn't guaranteed otherwise.

Once you have the results ordered, you can use APOC aggregation functions to get the first and last results of the ordered values:

MATCH (a:SomeNode)-[:SOME_LINK]->(b:OtherNodes)
WITH b
ORDER BY b.date DESC
RETURN apoc.agg.first(b) as first, apoc.agg.last(b) as last

View solution in original post

1 REPLY 1

You'll need to use ORDER BY in any case, as ordering isn't guaranteed otherwise.

Once you have the results ordered, you can use APOC aggregation functions to get the first and last results of the ordered values:

MATCH (a:SomeNode)-[:SOME_LINK]->(b:OtherNodes)
WITH b
ORDER BY b.date DESC
RETURN apoc.agg.first(b) as first, apoc.agg.last(b) as last