f7n
f7n

Reputation: 1674

How to collect a limited number of nodes using Cypher?

If I want to perform a MATCH query on the top 25 results of a previous MATCH, how would I do this in Cypher?

My first query is like:

START inputMovie=node(0)
MATCH (inputGenre:Genre)-[:IS_GENRE]-(inputMovie:Movie)
WITH inputMovie, COLLECT(inputGenre) AS inputGenres
MATCH (genre:Genre)-[o:IS_GENRE]-(outMovies:Movie)
WITH inputGenres, outMovies, genre
WHERE (genre IN inputGenres)
RETURN outMovies.title, count(genre) AS foo
ORDER BY foo desc
LIMIT 25

How would I then perform a MATCH query on only those 25 results? Can I collect a number of nodes? COLLECT(m) would collect every single node matching the WHERE constraint. Is there a way to collect the top 25 from a MATCH query?

Upvotes: 0

Views: 431

Answers (1)

cybersam
cybersam

Reputation: 66967

[EDITED]

First of all, your current query can be improved. The following shorter and faster query should be equivalent (and avoids using the deprecated START clause):

MATCH (outMovie:Movie)-[:IS_GENRE]-(:Genre)-[:IS_GENRE]-(inputMovie:Movie)
WHERE ID(inputMovie) = 0
MATCH (outMovie)-[:IS_GENRE]-(genre:Genre)
RETURN outMovie.title, count(genre) AS foo
ORDER BY foo DESC 
LIMIT 25

In general, you can replace RETURN with WITH if you want to extend an existing query. You just have to provide an alias for returned values that do not already have an identifier (in your case, outMovies.title would need to be aliased).

Here is a simple example with your query:

MATCH (outMovie:Movie)-[:IS_GENRE]-(:Genre)-[:IS_GENRE]-(inputMovie:Movie)
WHERE ID(inputMovie) = 0
MATCH (outMovie)-[:IS_GENRE]-(genre:Genre)
WITH outMovies.title AS title, count(genre) AS foo
ORDER BY foo DESC 
LIMIT 25
RETURN COUNT(title) AS num_titles;

The returned num_titles will be at most 25.

Upvotes: 1

Related Questions