Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

neo4j

cypher

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.

like image 909
Pierre Avatar asked Jan 06 '15 18:01

Pierre


2 Answers

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
like image 69
wassgren Avatar answered Oct 01 '22 08:10

wassgren


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.

like image 45
Pierre Avatar answered Oct 01 '22 08:10

Pierre