BackSlash
BackSlash

Reputation: 22233

Getting results count from a query with LIMIT clause

I have a Neo4j database with thousands of nodes.

I'm using this query to find nodes which contains some text inside the desired field:

MATCH (n:MYNODE)
WHERE n.myfield CONTAINS {textToSearch} 
RETURN n
ORDER BY n.myfield ASC 
LIMIT 50

This query works, and returns the first 50 results ordere by n.myfield.

Let's say 340 nodes match the search criteria: the first 50 get returned. Is there a way to return also the total count? I would like to have the 50 nodes along with the total count (340) for displaying purposes.

I would do a second query like this:

MATCH (n:MYNODE)
WHERE n.myfield CONTAINS {textToSearch} 
RETURN count(n)

Is there a way to avoid a second query and include this result in the first one? Neo4j should find all the 340 nodes before limiting them to 50 in the first query, so is there a way to intercept the nodes count before the LIMIT clause is applied and return it aswell?

Upvotes: 5

Views: 693

Answers (1)

Dave Bennett
Dave Bennett

Reputation: 11216

How about something like this. Order the result and put it in a collection. Then return the size of the collection and the first 50 items in the collection.

MATCH (n:MYNODE)
WHERE n.myfield CONTAINS {textToSearch}
WITH n
ORDER BY n.myfield
WITH COLLECT(n) as matched
RETURN size(matched), matched[..50]

Upvotes: 1

Related Questions