How can I use cypher to return some limited amount of nodes, and a count of all nodes?

StackOverflow https://stackoverflow.com/questions/23415690

  •  13-07-2023
  •  | 
  •  

Question

I currently have this query:

START n=node(*) 
MATCH (p:Person)-[:is_member]->(g:Group) 
WHERE g.name ='FooManGroup' 
RETURN p, count(p)
LIMIT 5

Say there are 42 people in FooManGroup, I want to return 5 of these people, with a count of 42.

Is this possible to do in one query?

Running this now returns 5 rows, which is fine, but a count of 104, which is the total number of nodes of any type in my DB.

Any suggestions?

Was it helpful?

Solution

You can use a WITH clause to do the counting of the persons, followed by an identical MATCH clause to do the matching of each person. Notice that you need to START on the p nodes and not just some n that will match any node in the graph:

MATCH (p:Person )-[:is_member]->(g:Group)
WHERE g.name ='FooManGroup' 
WITH count(p) as personsInGroup
MATCH (p:Person)-[:is_member]->(g:Group)
WHERE g.name ='FooManGroup'
RETURN p, personsInGroup
LIMIT 5

It may not be the best or most elegant way to this, but it works. If you use cypher 2.0 it may be a bit more compact like this:

MATCH (p:Person)-[:is_member]->(g:Group {name: 'FooManGroup'})
WITH count(p) as personsInGroup
MATCH (p:Person)-[:is_member]->(g:Group {name: 'FooManGroup'})
RETURN p, personsInGroup
LIMIT 5

Relationship types are always uppercased in cypher, so :is_member should be :IS_MEMBER which I think is more readable:

MATCH (p:Person)-[:IS_MEMBER]->(g:Group {name: 'FooManGroup'})
WITH count(p) as personsInGroup
MATCH (p:Person)-[:IS_MEMBER]->(g:Group {name: 'FooManGroup'})
RETURN p, personsInGroup
LIMIT 5

OTHER TIPS

Try this:

MATCH (p:Person)-[:is_member]->(g:Group) 
WHERE g.name ='FooManGroup' 
RETURN count(p), collect(p)[0..5]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top