Reputation: 943
Is it possible to extract in a single cypher query a limited set of nodes and the total number of nodes?
match (n:Molecule) with n, count(*) as nb limit 10 return {N: nb, nodes: collect(n)}
The above query properly returns the nodes, but returns 1 as number of nodes. I certainly understand why it returns 1, since there is no grouping, but can't figure out how to correct it.
Upvotes: 10
Views: 3090
Reputation: 509
This solution splits the work up into two parts: first get the complete list of rows, do a WITH that counts them and collects them into a list, and then do a subquery with collect() that does the paging. If you need to bring in additional information about the rows in the result, put that in between "WITH item" and "RETURN collect(item)" so that it is only done for the items on the page you are returning.
MATCH (n:MyLabel)
WITH collect(n) as collection,count(n) as cnt
CALL{
WITH collection
UNWIND collection as item
WITH item ORDER BY item.id DESC SKIP 10 LIMIT 5
RETURN collect(item) as items
}
RETURN cnt, items
Upvotes: 0
Reputation: 943
Here is an alternate solution:
match (n:Molecule) return {nodes: collect(n)[0..5], n: length(collect(n))}
84 ms for 30k nodes, shorter but not as efficient as the above one proposed by wassgren.
Upvotes: 3
Reputation: 19201
The following query returns the counter for the entire number of rows (which I guess is what was needed). Then it matches again and limits your search, but the original counter is still available since it is carried through via the WITH
-statement.
MATCH
(n:Molecule)
WITH
count(*) AS cnt
MATCH
(n:Molecule)
WITH
n, cnt LIMIT 10
RETURN
{ N: cnt, nodes:collect(n) } AS molecules
Upvotes: 9