examples · graph · 3 / 7
3. bfs - depth-bounded multi-hop
← Graph exampleswhat this does
Walks the graph forward in concentric rings around the source. Returns every distinct node reachable within max_depth hops, along with the depth at which it was first discovered. Each node is visited at most once.
when to use it
- "Everything within N hops" - friends-of-friends, suggested items, downstream blast radius.
- When you need the depth, not just the set - e.g. to weight closer hits higher.
- As a pre-filter for a more expensive scoring pass on a smaller candidate set.
schema requirement
The relation must be declared in the schema's [[relations]] block. See schemas/reference#relations.
the request
GET /v1/tenants/:t/graph/:schema/bfs?rel=...&pk=...&max_depth=N
curl "https://$OC_HOST/v1/tenants/$OC_TENANT/graph/shop.orders/bfs?rel=bought_product&pk=o001&max_depth=3" \
-H "Authorization: Bearer $OC_TOKEN"result = db.graph.bfs(
"shop.orders",
rel="bought_product",
pk="o001",
max_depth=3,
)const result = await db.graph.bfs("shop.orders", {
rel: "bought_product",
pk: "o001",
max_depth: 3,
});result, _ := db.Graph().BFS(ctx, "shop.orders", originchain.BFSRequest{
Rel: "bought_product",
PK: "o001",
MaxDepth: 3,
}) what you get back
[
{ "pk": "p001", "depth": 1 },
{ "pk": "p014", "depth": 1 },
{ "pk": "u091", "depth": 2 },
{ "pk": "u117", "depth": 2 },
{ "pk": "c003", "depth": 3 }
]
An array of { pk, depth } objects. Depth is the shortest hop-count from the source; the source itself isn't in the result.
how it works
- The engine maintains a visited set and a frontier queue, expanding one depth at a time.
- Each ring is built by a batched adjacency lookup against the previous frontier - one point-read per node, no scans.
- Traversal stops when the frontier is empty or depth reaches
max_depth.
common mistakes
- Forgetting
max_depth. On dense graphs, a missing or very large depth can return millions of nodes. Set a real bound - 2 or 3 is usually enough. - Treating depth as cost. bfs counts hops, not weights. If your edges have meaningful weights, use dijkstra.