GQL API

Questioned Paths

Overview

A questioned path makes a segment of a path pattern optional. It matches either zero or one occurrence of the parenthesized pattern. This is useful when you want to look for optional connections in a path without filtering out results that don't have them.

A questioned path is written by appending a question mark ? to a parenthesized path pattern expression.

-- Syntax
( path_pattern_expression )?

When the path exists, it is evaluated and bound to variables; when it doesn't, the match still succeeds, and the variables inside the optional path evaluate to null.

RageDB Singleton Scalar Binding Semantics

A crucial difference exists between using the quantifier {0,1} and the questioned path operator ?:

  • {0,1} (Quantified Path): Variables declared inside the repeated group are treated as group variables. They are always returned as list types (either a single-element list or an empty list).
  • ? (Questioned Path): Variables declared inside remain singletons. They preserve their original scalar types but become conditional singletons. If the optional path is absent, the variable resolves directly to null.

Examples

Find all wizards teaching a spell, and optionally retrieve another wizard they are AlliedWith (if one exists):

MATCH (w1:Wizard)-[:Teaches]->(s:Spell) ( -[:AlliedWith]->(w2:Wizard) )?
RETURN w1.name AS teacher, s.name AS spell, w2.name AS ally
Example Result Set:
teacher spell ally
Albus Shield of Light Harry
Severus Shadow Curse null
Hermione Fireball Ron
Harry Frostbolt Hermione

Because w2 is declared within the questioned path ( -[:AlliedWith]->(w2:Wizard) )?, it remains a singleton scalar. When "Severus" has no outgoing AlliedWith edge, w2.name evaluates directly to null instead of an empty list.