LIMIT applies to the total number of rows of the query, it can’t be used in cases when matching from multiple nodes where the limit must be per row.
Take an example case using the Movies database.
If you needed a query to get all the actors from The Matrix, and for each actor, get 3 movies that actor has acted in, a first (incorrect) attempt might look like this:
The above query won’t return the desired results. The
LIMIT will instead make the query return only 3 rows total.
Some solutions to apply a limit to match results per-row
Take the interested slice of a collection
One common solution is to
collect() and take the interested slice:
In Neo4j 3.1.x and newer you can use pattern comprehension as a shorthand approach:
If only one element in the collection is needed, the
head() function can be used to get the first element from the pattern comprehension:
While this works when there are few relationships per node, it may become infeasible on supernodes with larger numbers of relationships, as it must expand all
:ACTED_IN relationships before collecting.
Use apoc.cypher.run() to execute a limited subquery
Neo4j doesn’t currently offer native subquery support aside from pattern comprehension, but even those don’t support
However, in Neo4j 3.0.x and newer, using APOC Procedures, you can use
apoc.cypher.run() to execute a subquery with a
LIMIT, which performs the way we want since it executes per-row.
This approach is efficient since by using
LIMIT we don’t have to pay the cost of expanding all
:ACTED_IN relationships, we only need to expand 3 per row.
Use APOC path expander using end node or termination filters and
With Neo4j 3.1.3 and higher, and APOC Procedures 126.96.36.199 and higher, you can use use new path expander features to limit expansion to certain nodes.
limit param is only usable with path expander procedures that take a config map, and only when using the end node (
>) or termination label filters (
Using this approach, the query becomes: