GQL API

Shortest Paths

Overview

Shortest paths between two nodes are those containing the fewest number of edges (unweighted shortest path search). In GQL, shortest paths are retrieved using specialized path selectors applied to quantified paths.

When a shortest path selector is used, RageDB's query engine performs a trail-based Breadth-First Search (BFS) where repeated edges are prohibited (the path mode defaults to TRAIL).

To minimize a weighted sum of edge costs (such as mana cost) rather than hop counts, see Cheapest Paths.

Shortest Path Selectors

Selector Description
ALL SHORTEST Selects all shortest paths from each start-end node partition.
ANY SHORTEST Selects exactly one shortest path from each partition.
SHORTEST k Selects up to k paths from each partition, starting with the absolute shortest. If there are fewer than k shortest paths, it proceeds to select from the next shortest paths (2nd shortest, 3rd shortest, etc.) until k are found.
SHORTEST k GROUP Groups paths by length, sorts them in ascending order, and selects all paths belonging to the first k length groups.

Examples

1. ALL SHORTEST

Find all shortest knows-connection paths between "Albus" and "Draco" (using the + quantifier for 1 or more hops):

MATCH p = ALL SHORTEST (a:Wizard {name: "Albus"})-[:Knows]-+(b:Wizard {name: "Draco"})
RETURN p

2. ANY SHORTEST

Find any one shortest path between "Albus" and "Luna" within 1 to 10 hops:

MATCH p = ANY SHORTEST (a:Wizard {name: "Albus"})-[:Knows]-{1,10}(b:Wizard {name: "Luna"})
RETURN p

3. SHORTEST k

Find the 2 shortest path connections between "Albus" and "Luna":

MATCH p = SHORTEST 2 (a:Wizard {name: "Albus"})-[:Knows]-{1,10}(b:Wizard {name: "Luna"})
RETURN p

4. SHORTEST k GROUP

Group the paths between "Albus" and "Luna" by length, and return all paths belonging to the 2 shortest lengths found:

MATCH p = SHORTEST 2 GROUP (a:Wizard {name: "Albus"})-[:Knows]-{1,10}(b:Wizard {name: "Luna"})
RETURN p

Partition-Based Selection Semantics

When a path pattern matches multiple starting and ending nodes, the matching paths are conceptually **partitioned** by each unique combination of start and end node. The shortest path selection is executed independently within each partition, and the final result set is the union of all partitions.

This query finds the shortest path from "Albus" to any other wizard in the graph:

MATCH p = SHORTEST 1 ({name: "Albus"})-[:Knows]-{1,10}()
RETURN p

Since there are multiple reachable target nodes, the result set is partitioned by each reachable wizard, and the single shortest path is returned for each individual target.