Get top/bottom node by property value


(Dbeaumon) #1

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


(Andrew Bowman) #2

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