liveBook · Manning

Count pattern operator

As explained in Graph Algorithms for Data Science

The count pattern operator is Cypher syntax that counts matches for an embedded graph pattern.

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

How Graph Algorithms for Data Science covers it

How deep it goes
Explains syntax, cardinality risks, and a working query, but defers performance measurement to PROFILE.
Examples
Uses mention counting for users and a multi-stage Twitter mention-distribution exercise.
What it assumes
Assumes familiarity with counting and filtering graph patterns, while explaining cardinality through concrete queries.
What you can do after
Apply it via Cypher to count related patterns without multiplying intermediate query rows.
How it connects
Connects aggregation, cardinality, graph patterns, OPTIONAL MATCH, and existential subqueries.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Graph Algorithms for Data Science. The section links point to the parts of the book it draws on.