A grouping key is a non-aggregated expression that determines which rows contribute to each aggregate result. In Cypher, grouping keys are implicit: once a query uses an aggregation function, every non-aggregated value in its WITH or RETURN clause becomes a grouping key. section 4.2
Use grouping keys to organize aggregate results around graph attributes:
- Count nodes by label with labels(n) alongside count(n); the returned labels value becomes the grouping key. section 4.2
- Count tweets by year by returning the extracted year with count; add both year and month to group by month within a year. section 4.2.1
- Use non-aggregate values in WITH or RETURN instead of adding a separate GROUP BY clause. section 4.2
Counting tweets by year and month
A query returning t.createdAt.year, t.createdAt.month, and count(*) groups tweets by each year-month pair. The resulting distribution shows 8,507 tweets in May 2021 and 2,695 in June 2021. section 4.2.1
Listing 4.5 Counting the number of nodes by labels
MATCH (n)
RETURN labels(n) AS labels,
count(n) AS count;
Inspect a direct Cypher pattern for grouping nodes by their labels while counting them. section 4.2
