Examples

BFS - Shortest Path

Use breadth-first search to find paths and explore nodes within a distance.

Use BFS (Breadth-First Search) to explore nodes within a certain distance from a starting point.

Setting Up the Graph

from cog.torque import Graph

g = Graph("network")
g.put_batch([
    ("a", "link", "b"), ("b", "link", "c"),
    ("a", "link", "d"), ("d", "link", "e"), ("e", "link", "c"),
])

This creates a graph:

a → b → c
│       ↑
└→ d → e┘

Find Nodes Within N Hops

Use bfs() to find all nodes reachable within a maximum depth:

# Find all nodes within 2 hops of 'a'
g.v("a").bfs(predicates="link", max_depth=2).all()
# {'result': [{'id': 'b'}, {'id': 'd'}, {'id': 'c'}, {'id': 'e'}]}

BFS Parameters

  • predicates - Edge type(s) to follow (string or list)
  • max_depth - Maximum number of hops

Finding Shortest Paths

# Nodes exactly 1 hop away
g.v("a").bfs(predicates="link", max_depth=1).all()
# {'result': [{'id': 'b'}, {'id': 'd'}]}

# Nodes up to 3 hops away
g.v("a").bfs(predicates="link", max_depth=3).all()
# {'result': [{'id': 'b'}, {'id': 'd'}, {'id': 'c'}, {'id': 'e'}]}

On this page