Cypher - Limit Number of Nodes created by a Single Author

I have a database of multiple pieces of content all of which have an author relationship.

I want to be able to write a query that returns "recent" content (say 20 posts) but I don't want posts by the same author to appear more than 3 times in the results.

Is there a way to do this in Cypher?

Hello and Welcome to the Neo4j Community!

Not sure how you define recent, but to return at most 3 posts per author:

MATCH (p:Person)-[:POSTED]->(c:Content
WITH p, collect(c.subject) as theContent
WHERE size(theContent) <= 3
RETURN p.name, theContent

To get the most recent content, you would place an ORDER BY clause in the WITH clause to order them.

Elaine

Thank you very much.

In my case it will be in descending order of creation date (the nodes will have a creation date property). But only a max of 3 posts created by the same author appearing in the results. For a max of 20 (or whatever limit we set)

Try this:

MATCH (p:Person)-[:POSTED]->(c:Content)
WITH p, c ORDER by c.datePosted DESC
WITH p, collect(c.subject) as theContent
WHERE size(theContent) <= 3
RETURN p.name, theContent

Note that the suggested query is a filtering query, so it will only find authors that created 3 posts or less.

If you want to include those authors but limit the content, you need a way to limit results per row.

We have a knowledge base article with a few different ways to perform this:

So for example you can take the relevant slice of each collection:

MATCH (p:Person)-[:POSTED]->(c:Content)
WITH p, c ORDER by c.datePosted DESC
WITH p, collect(c.subject)[..3] as theContent
RETURN p.name, theContent