Examples
Multi-hop Traversal with Tags
Traverse multiple hops in your graph and tag intermediate nodes.
Learn how to traverse multiple edges and capture intermediate nodes using tags.
Setting Up the Graph
from cog.torque import Graph
g = Graph("friends")
g.put_batch([
("alice", "knows", "bob"),
("bob", "knows", "charlie"),
("charlie", "knows", "diana"),
])Friends of Friends (2 Hops)
Use chained out() calls to traverse multiple hops. Use tag() to capture intermediate nodes:
# Friends of friends (2 hops)
g.v("alice").out("knows").tag("friend").out("knows").all()
# {'result': [{'id': 'charlie', 'friend': 'bob'}]}Explanation
g.v("alice")- Start at Alice.out("knows")- Find Alice's direct friends (Bob).tag("friend")- Tag this node as "friend".out("knows")- Find their friends (Charlie).all()- Return results with tags
The result shows Charlie (friend of friend) with friend: bob indicating the path.
Three Hops
# Friends of friends of friends (3 hops)
g.v("alice").out("knows").tag("hop1").out("knows").tag("hop2").out("knows").all()
# {'result': [{'id': 'diana', 'hop1': 'bob', 'hop2': 'charlie'}]}