Patterns

Patterns and pattern-matching are at the very heart of Cypher, so being effective with Cypher requires a good understanding of patterns. The pattern describes the data using a form that is very similar to how one typically draws the shape of property graph data on a whiteboard: usually as circles (representing nodes) and arrows between them to represent relationships. Patterns appear in multiple places in Cypher: in MATCH, CREATE and MERGE clauses, and in pattern expressions.

Patterns for relationships

The simplest way to describe a relationship is by using the arrow between two nodes, as in the previous examples. Using this technique, you can describe that the relationship should exist and the directionality of it. If you don’t care about the direction of the relationship, the arrow head can be omitted:

(a)--(b)

As with nodes, relationships may also be given names. In this case, a pair of square brackets is used to break up the arrow and the variable is placed between. For example:

(a)-[r]->(b)

Much like labels on nodes, relationships can have types. To describe a relationship with a specific type, you can specify this as follows:

(a)-[r:REL_TYPE]->(b)

or when multiple types are required:

(a)-[r:TYPE1|TYPE2]->(b)

Variable Length Paths

Rather than describing a long path using a sequence of many nodes and relationship descriptions in a pattern, many relationships (and the intermediate nodes) can be described by specifying a length in the relationship description of a pattern. For example:

(a)-[*2]->(b)

This is similar to :

(a)-()->(b)

The code below describes a path with a minimum length of 3, and a maximum of 5. It describes a graph of either

  • 4 nodes and 3 relationships

  • 5 nodes and 4 relationships

  • 6 nodes and 5 relationships

(a)-[*3..5]->(b)

Last change: Oct 30, 2023