1
votes

I have some :books. Books are idenifyed by an ISBNs and have :similar relationships to related books. Here is my cypher query to get similar books to the provided list of ISBNs:

MATCH (b:Book)-[:SIMILAR]-(c:Book) 
WHERE b.ISBN in $ISBNs
return b, c

However, I would like to limit the number of similar books per book to 5, without limiting the total books. In other words, I currently get 7 similar on one book, 6 on another, and 3 on one if I provide a certain list of ISBNs. I would like to limit that to 5 per book, so I get 5, 5, and 3. How can I do this?

2

2 Answers

2
votes

Change your query to:

MATCH (b:Book)-[:SIMILAR]-(c:Book) 
WHERE b.ISBN in $ISBNs
RETURN {book:b, similars: collect(c)[..5]}

This query uses the collect() function to collects all the similar books into a list. It will return a projection with a book key that contains the main book and a similars key that contains a collection of similar books limited to 5 books.

1
votes

With APOC Procedures you can limit the number of match results per-row, rather than applying the limit to the total rows.

Take a look at this knowledge base article for how to achieve this with apoc.cypher.run().

If you can't use APOC Procedures, you can use Bruno's answer, which takes the limited slice of a collection.