GQL API

K-Hop Traversal

Overview

The K-hop neighbors of a node are the set of nodes whose shortest path distance from the starting node is exactly K.

RageDB provides a native MATCH KHOP statement. It is designed for high-performance reachability queries (e.g. "Who is reachable within K hops?") and neighbor counts. Rather than materializing all possible paths, MATCH KHOP tracks only unique reachable target nodes, providing substantial performance improvements over regular path matching.

-- Syntax
MATCH KHOP start_node -[ edge_pattern ]->{ quantifier } target_node

Key Properties of MATCH KHOP

  • Deduplication: Each destination node is returned at most once per start node, regardless of how many shortest paths lead to it.
  • Shortest Distance Isolation: Nodes are categorized by their shortest distance. A node that is reachable at 1 hop will not be returned in a 2-hop search, even if a longer 2-hop path also leads to it.
  • Cycle Exclusion: The starting node is excluded from the results, even if a cycle connects it back to itself.

Count-Only Shard Optimization

When a MATCH KHOP query is used primarily to count neighbors, and the target node variable is only referenced inside a COUNT(target) or COUNT(*) function, RageDB activates a **count-only execution path**.

Under this optimization, RageDB bypasses node record instantiation and reads directly from the shard indices. This significantly reduces memory allocations and CPU overhead, completing neighbor counts on large graphs almost instantly.

Examples

1. Exact Hop Distance

Find all wizards who are exactly 2 hops away from "Albus" via knows-relationships:

MATCH KHOP (a:Wizard {name: "Albus"})-[:Knows]->{2}(n:Wizard)
RETURN n.name

2. Hop Range Traversal

Find all wizards located within 1 to 2 knows-relationship hops from "Albus":

MATCH KHOP (a:Wizard {name: "Albus"})-[:Knows]->{1,2}(n:Wizard)
RETURN n.name

3. Optimized Count Query

Count the total number of distinct wizards reachable within 1 to 3 hops from "Albus". This statement automatically triggers the count-only shard optimization:

MATCH KHOP (a:Wizard {name: "Albus"})-[:Knows]->{1,3}(n:Wizard)
RETURN count(n)