Patterns

Graph pattern matching sits at the very core of Cypher®. It is the mechanism used to navigate, describe and extract data from a graph by applying a declarative pattern. Inside a MATCH clause, you can use graph patterns to define the data you are searching for and the data to return. Graph pattern matching can also be used without a MATCH clause, in the subqueries EXISTS, COUNT, and COLLECT.

A graph pattern describes data using a syntax that is similar to how the nodes and relationships of a property graph are drawn on a whiteboard. On a whiteboard, nodes are drawn as circles and relationships are drawn as arrows. Cypher represents the circles as a pair of parentheses, and the arrows as dashes and greater-than or less-than symbols:

()-->()<--()

These simple patterns for nodes and relationships form the building blocks of path patterns that can match paths of a fixed length. As well as discussing simple fixed-length patterns, this chapter covers more complex patterns, showing how to match patterns of a variable or unknown length, find the shortest paths between a given set of nodes, add inline filters for improved query performance, and add cycles and non-linear shapes to path patterns.

This chapter includes the following sections:

  • Primer - a short primer on how to get started with using graph pattern matching in Cypher.

  • Fixed-length patterns - information about node, relationship, and path patterns.

  • Variable-length patterns - information about quantified path patterns, quantified relationships, and group variables.

  • Shortest paths - information about finding the SHORTEST path patterns.

  • Non-linear patterns - information about equijoins and graph patterns (combined path patterns).

  • Syntax and semantics - a reference for looking up the syntax and semantics of graph pattern matching.

Cypher 25 introduces the ability to specify different match modes. For more information, see the Cypher 25 Manual → Match modes.

The model data in the examples used in this chapter are based on the UK national rail network, using publicly available datasets.