Node Patterns

Node patterns are a core concept in Cypher, defining how to match or create data within the graph. Understanding how to create and use patterns will allow you to write expressive queries that can efficiently retrieve and manipulate your graph data.

Relationship Patterns

Relationship patterns describe how nodes are connected through relationships. A typical relationship pattern consists of two nodes and the relationship between them. For example:

MATCH (a:Person)-[:KNOWS]->(b:Person)
RETURN a, b

The above query returns all pairs of people who know each other. The nodes are represented by (a:Person) and (b:Person), and the relationship is represented by -[:KNOWS]->.

Relationship patterns can also include a variable for the relationship, allowing you to return or manipulate the relationship itself:

MATCH (a:Person)-[rel:KNOWS]->(b:Person)
RETURN a, rel, b

Variable Length Relationships

Sometimes, you might want to match a pattern where there can be varying lengths of relationships. This is where variable length relationships come in handy. For example, to find all people who are a friend of a friend (of a friend…), you can use a variable length relationship:

MATCH (a:Person)-[:KNOWS*2..5]->(b:Person)
RETURN a, b

The *2..5 after the KNOWS relationship indicates that the query should return pairs of people who are connected by between 2 and 5 ‘KNOWS’ relationships.

Path Expressions

Path expressions are a way to match a series of nodes and relationships, representing the path through the graph. For example, you might want to find a path of KNOWS relationships leading from one person to another:

MATCH path = (a:Person { name: 'John Doe' })-[:KNOWS*]->(b:Person { name: 'Jane Doe' })
RETURN path

This query returns the path of ‘KNOWS’ relationships from ‘John Doe’ to ‘Jane Doe’. Paths can be of any length, and the nodes along the path can be of any type, unless specified otherwise.

Path expressions can also be useful when working with variable length relationships, as they allow you to return or manipulate not just the start and end nodes, but also the nodes and relationships along the path:

MATCH path = (a:Person)-[:KNOWS*2..5]->(b:Person)
RETURN nodes(path), relationships(path)

This query returns the nodes and relationships along the path of 2 to 5 ‘KNOWS’ relationships between people.

Node patterns, whether they are simple or complex, form the backbone of Cypher queries. Mastering these patterns will allow you to write powerful and efficient queries to explore and manipulate your graph data in Polypheny.

© Polypheny GmbH. All Rights Reserved.