GQL API

Path Patterns

Overview

A path pattern matches sequences of alternating nodes and edges in the graph. It consists of three parts:

  1. Path variable declaration (optional)
  2. Path pattern prefix (optional)
  3. Path pattern expression
-- Syntax
[ path_variable = ] [ path_prefix ] path_expression

Basic Paths

A path expression chains node and edge patterns sequentially. A valid path pattern must alternate between nodes and edges, starting and ending with a node pattern.

Chaining Elements:

Match paths starting from a wizard named "Harry", leading to a spell via Teaches:

(:Wizard {name: "Harry"})-[:Teaches]->(:Spell)

Find wizards who share a mutual knows-connection with "Harry" and "Hermione", binding the mutual friend to friend:

(:Wizard {name: "Harry"})-[:Knows]->(friend:Wizard)<-[knows]-(:Wizard {name: "Hermione"})
Ring and Cycle Structures:

You can reuse a node variable at different points in a path pattern to enforce cycle constraints. This query finds a closed alliance loop starting and ending at the same wizard w:

(w:Wizard)-[:AlliedWith]->(:Wizard)-[:AlliedWith]->(w)

Path Variable Declaration

A path variable binds the entire matched path to a single variable using the = operator.

Find paths of knows-connections and bind the resulting path to the variable p:

MATCH p = (:Wizard)-[:Knows]->(:Wizard)
RETURN p

Path Mode

Path modes control how paths are traversed and whether nodes or edges can be revisited. A path mode is placed at the beginning of the path pattern expression.

Path Mode Description
TRAIL Default. Edges cannot be repeated within a path. Nodes may be repeated.
ACYCLIC Strictly no repeated nodes are allowed in the path.
SIMPLE No repeated nodes are allowed, except that the starting and ending nodes may be the same (forming a cycle).
WALK No restrictions. Both nodes and edges can be repeated.
Example Query using ACYCLIC:
MATCH p = ACYCLIC (w1:Wizard {name: "Albus"})-[:AlliedWith]->{1,3}(w2:Wizard)
RETURN p

Path Selector

A path selector filters the paths returned for each start-end node partition.

Path Selector Description
ALL Default. Returns all matching paths.
ANY Returns exactly one path for each pair of start and end nodes.
ANY k Returns up to k paths for each start and end node pair.
Example Query using ANY:
MATCH p = ANY (:Wizard {name: "Albus"})-[:AlliedWith]->{1,3}(target:Wizard)
RETURN p
Combined Usage:

When using both, the selector must precede the mode (e.g., ANY ACYCLIC):

MATCH p = ANY ACYCLIC (:Wizard {name: "Albus"})-[:AlliedWith]->{1,3}(target:Wizard)
RETURN p

Special Considerations

Edge Juxtaposition:

Consecutive edge patterns implicitly assume an empty node pattern () between them.

-- Juxtaposition
(:Wizard)-[]->-[]->(w)

-- Desugars to
(:Wizard)-[]->()-[]->(w)

Note: Avoid juxtaposing tokens that expose minus signs next to each other (e.g. ]--[ or ->-) as it can be parsed as a comment sign (--).