apoc.agg.nth

Function APOC Core

apoc.agg.nth(value,offset) - returns value of nth row (or -1 for last)

Signature

apoc.agg.nth(value :: ANY?, value :: INTEGER?) :: (ANY?)

Input parameters

Name Type Default

value

ANY?

null

value

INTEGER?

null

Usage Examples

The examples in this section are based on the following sample graph:

CREATE (Keanu:Person {name:'Keanu Reeves', born:1964})
CREATE (TomH:Person {name:'Tom Hanks', born:1956})

CREATE (TheMatrix:Movie {title:'The Matrix', released:1999, tagline:'Welcome to the Real World'})
CREATE (TheMatrixReloaded:Movie {title:'The Matrix Reloaded', released:2003, tagline:'Free your mind'})
CREATE (TheMatrixRevolutions:Movie {title:'The Matrix Revolutions', released:2003, tagline:'Everything that has a beginning has an end'})
CREATE (YouveGotMail:Movie {title:"You've Got Mail", released:1998, tagline:'At odds in life... in love on-line.'})
CREATE (SleeplessInSeattle:Movie {title:'Sleepless in Seattle', released:1993, tagline:'What if someone you never met, someone you never saw, someone you never knew was the only someone for you?'})

CREATE (Keanu)-[:ACTED_IN {roles:['Neo']}]->(TheMatrix)
CREATE (Keanu)-[:ACTED_IN {roles:['Neo']}]->(TheMatrixReloaded)
CREATE (Keanu)-[:ACTED_IN {roles:['Neo']}]->(TheMatrixRevolutions)

CREATE (TomH)-[:ACTED_IN {roles:['Joe Fox']}]->(YouveGotMail)
CREATE (TomH)-[:ACTED_IN {roles:['Sam Baldwin']}]->(SleeplessInSeattle);

This function provides a more efficient way of getting the nth value in a collection. For example, to find the 2nd earliest movie that each person has acted in, we could write the following query:

Cypher
MATCH (p:Person)-[:ACTED_IN]->(movie)
WITH p, movie
ORDER BY p, movie.released
RETURN p.name AS person, collect(movie)[1] AS nthMovie;

This query collects all of the movies into memory, before returning just the second one. We can avoid this build up of in memory state by using the apoc.agg.nth aggregation function, as shown below:

apoc.agg.nth
MATCH (p:Person)-[:ACTED_IN]->(movie)
WITH p, movie
ORDER BY p, movie.released
RETURN p.name AS person, apoc.agg.nth(movie, 1) AS nthMovie;
Table 1. Results
person nthMovie

"Keanu Reeves"

(:Movie {tagline: "Welcome to the Real World", title: "The Matrix", released: 1999})

"Tom Hanks"

(:Movie {tagline: "In every life there comes a time when that thing you dream becomes that thing you do", title: "That Thing You Do", released: 1996})