The count pattern operator, written as count { pattern }, counts matches for an embedded graph pattern. It is useful when several aggregations would otherwise multiply intermediate rows. section 4.4 section 4.7
Use the operator to keep aggregation results accurate and the main query cardinality stable:
- Match each node or row once, then count its related pattern inside curly braces. section 4.4
- Prefer count { } when multiple aggregations occur in one query and expanding the pattern could increase intermediate rows. section 4.4 section 4.5
- Distinguish it from count(), which aggregates rows or expressions after a clause. section 4.7
Count mentions without expanding the main query
MATCH (u:User) WITH u, count { (u)<-[:MENTIONS]-() } AS mentions ORDER BY mentions DESC LIMIT 5 RETURN u.username AS user, mentions This returns each user with the number of incoming MENTIONS relationships while avoiding the cardinality increase caused by matching every mention as a row. section 4.4
Listing 4.15 Convenient way of retrieving the top five most mentioned users by not increasing main query cardinality
MATCH (u:User)
WITH u, count { (u)<-[:MENTIONS]-() } AS mentions
ORDER BY mentions DESC LIMIT 5
RETURN u.username AS user, mentions
Inspect the complete Cypher listing for counting mentions while preserving the main query cardinality. section 4.4
