Count Nodes by multiple properties in Neo4J database

Viewed 26

I have a Neo4J database structured like in this picture.picture It's representing the people from a school. want a query that would allow me to count the nodes on multiple properties/labels.

I need the response to look something like this.

{
  teachers: 2,
  staff: 5,
  students: {
    total: 3,
    overNine:1,
    overEight:1,
    over seven:1
  },
  peopleInSchool:[
    {
      name: name1,
      details: someDetailedProperty1
    },
    {
      name: name2,
      details:someDetailedProperty2
    }
  ]

} 
1 Answers

You can try something along these grounds:

MATCH (n) 
WITH COLLECT(n) AS nodes
WITH nodes, 
size([x IN nodes WHERE x:Staff | x]) AS staff, size([x IN nodes WHERE x:Teacher | x]) AS teacher, 
size([x IN nodes WHERE x:Student | x]) AS student, size([x IN nodes WHERE x:Student AND x.avg > 7 AND x.avg < 8 | x]) AS overSeven,  
size([x IN nodes WHERE x:Student AND x.avg > 8 AND x.avg < 9 | x]) AS overEight,
size([x IN nodes WHERE x:Student AND x.avg > 9 | x]) AS overNine
RETURN { teachers: teacher, staff: staff, students: { total: student, overSeven: overSeven, overEight: overEight, overNine: overNine }}

Here, we are fetching all nodes and collecting them in a list, then we calculate the size of list after filtering elements, matching certain criteria. For example:

size([x IN nodes WHERE x:Staff | x])

This statement calculates the size of the list, in which only staff nodes are present.

Related