Search code examples
neo4jcypher

Cypher to return total node count as well as a limited set


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.


Solution

  • 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