Filtering and Aggregating Graph Data
You'll learn how to narrow down graph query results and summarize data using filters and aggregation functions.
When querying graphs, you often need to filter results based on specific criteria and summarize information across multiple nodes or relationships. This is where WHERE clauses, property filters, and aggregation functions become essential.
Filtering with WHERE
The WHERE clause lets you filter nodes or relationships based on property values, similar to SQL. You can check conditions like age, status, or any other property to narrow your results before traversing further:
MATCH (person:Person)-[:FRIENDS_WITH]->(friend)
WHERE person.name = 'Alice' AND friend.age > 25
RETURN friend.name
This finds Alice's friends who are older than 25.
Property Filters in Patterns
You can also filter directly within the pattern using curly braces for cleaner queries:
MATCH (person:Person {name: 'Alice'})-[:FRIENDS_WITH]->(friend)
WHERE friend.age > 25
RETURN friend.name
Aggregation Functions
Graph queries support aggregation to summarize results:
COUNT()– counts nodes, relationships, or valuesCOLLECT()– gathers values into a listSUM(),AVG(),MAX(),MIN()– numeric aggregations
MATCH (person:Person {name: 'Alice'})-[:FRIENDS_WITH]->(friend)
RETURN COUNT(friend) AS friendCount
Or collect all friend names into a list:
MATCH (person:Person {name: 'Alice'})-[:FRIENDS_WITH]->(friend)
RETURN COLLECT(friend.name) AS friendNames
Analogy: Think of filtering as using a sieve to keep only the pebbles you want, and aggregation as counting or organizing those pebbles into buckets.
Key Takeaway: Use WHERE clauses to filter graph data by properties, and aggregation functions like COUNT and COLLECT to summarize results across multiple nodes or relationships efficiently.