Torque API Reference

CogDB's graph traversal API.

Torque is CogDB's graph traversal language implemented as a Python API.

Graph

Graph(graph_name, cog_home="cog_home", cog_path_prefix=None, enable_caching=True, flush_interval=1)

Creates a Graph object. Parameters:

  • cog_home - Home directory name
  • cog_path_prefix - Parent directory
  • enable_caching - Enable caching (default: True)
  • flush_interval - Controls write flushing (default: 1)

flush_interval Options

ValueBehaviorUse Case
1Flush every writeInteractive use
> 1Async flush every N writesBulk inserts
0Manual flush via sync()Maximum speed

Examples:

from cog.torque import Graph

g = Graph("my_graph")

# Custom location
g = Graph("my_graph", cog_home="data", cog_path_prefix="/var/lib")

# For bulk inserts set flush interval to higher value, default is 0, which would flush on every write.
g = Graph("my_graph", flush_interval=1000)

Understanding Traversal State

Each traversal method moves the cursor. The v() method resets the cursor.

g.v("alice").out("knows").all()   # {'result': [{'id': 'bob'}]}
g.v("bob").out("likes").all()     # {'result': [{'id': 'tacos'}]}

Terminal methods (all(), count(), graph()) do NOT reset the traversal. Only v() resets the cursor.


put

put(vertex1, predicate, vertex2, update=False, create_new_edge=False)

Adds an edge connecting two vertices.

Prop

Type

Examples:

g.put("alice", "follows", "bob")
g.put("bob", "status", "cool_person")

put_batch

put_batch(triples)

Adds multiple edges at once. Faster than repeated put() calls.

Prop

Type

Example:

g.put_batch([
    ("alice", "follows", "bob"),
    ("bob", "follows", "charlie"),
    ("charlie", "follows", "alice"),
    ("alice", "status", "active")
])

sync

sync()

Force pending writes to disk.

Example:

g = Graph("my_graph", flush_interval=0)
for i in range(10000):
    g.put(f"node_{i}", "connects", f"node_{i+1}")
g.sync()  # Flush all pending writes

drop

drop()

Deletes the entire graph and all its data. This is a destructive operation — use with caution.

Example:

g.drop()  # Permanently deletes the graph

drop() is irreversible. To remove individual edges, use delete(). To clear data while keeping the graph reusable, use truncate().


delete

delete(vertex1, predicate, vertex2)

Removes a single edge (triple) from the graph.

Prop

Type

Example:

g.delete("alice", "follows", "bob")  # Remove a specific edge

truncate

truncate()

Clears all data from the graph while preserving its structure. The graph remains usable and can be repopulated.

Example:

g.truncate()  # Clear all data, graph is still usable
g.put("alice", "follows", "bob")  # Add new data

v

v(vertex=None)

Start traversal at a vertex. If no vertex is given, traversal starts from all vertices.

Prop

Type

Examples:

# Start from a specific vertex
g.v("alice").out("follows").all()

# Start from multiple vertices
g.v(["alice", "bob"]).out("follows").all()

# Start from all vertices
g.v().out("follows").all()

out

out(predicates=None)

Traverse forward through outgoing edges.

Prop

Type

Examples:

# Traverse all outgoing edges
g.v("bob").out().all()

# Traverse a specific edge type
g.v("bob").out("follows").all()

# Multiple edge types
g.v("bob").out(["follows", "status"]).all()

inc

inc(predicates=None)

Traverse backward through incoming edges.

Prop

Type

Examples:

# Find all vertices that follow "bob"
g.v("bob").inc("follows").all()

# Multiple edge types
g.v("cool_person").inc(["status"]).all()

both

both(predicates=None)

Traverse in both directions (combines out() and inc()).

Prop

Type

Examples:

# Find all connections (in either direction)
g.v("alice").both("knows").all()

# Multiple predicates
g.v("alice").both(["knows", "works_with"]).all()

bfs

bfs(predicates=None, max_depth=None, min_depth=0, direction="out", until=None, unique=True)

Breadth-first search traversal.

ParameterDescriptionDefault
predicatesEdge types to followNone
max_depthMaximum depthNone
min_depthMinimum depth0
direction"out", "inc", or "both""out"
untilStop condition lambdaNone
uniqueVisit each vertex onceTrue

Examples:

# Find all vertices within 2 hops
g.v("alice").bfs(predicates="follows", max_depth=2).all()

# Find vertices at exactly depth 2-3
g.v("alice").bfs(max_depth=3, min_depth=2).all()

# Stop when target is found
g.v("alice").bfs(until=lambda v: v == "target_user").all()

dfs

dfs(predicates=None, max_depth=None, min_depth=0, direction="out", until=None, unique=True)

Depth-first search traversal. Same parameters as bfs().

Examples:

g.v("alice").dfs(predicates="follows", max_depth=5).all()
g.v("target").dfs(direction="inc", max_depth=3).all()

is_

is_(*nodes)

Filter to specific vertices.

Prop

Type

Examples:

g.v("alice").out("follows").is_("bob").all()
g.v("alice").out("follows").is_("bob", "charlie").all()

unique

unique()

Remove duplicate vertices.

Example:

g.v(["alice", "bob"]).out("follows").unique().all()

limit

limit(n)

Limit to first n vertices.

Prop

Type

Example:

g.v("alice").out("follows").limit(5).all()

skip

skip(n)

Skip first n vertices.

Prop

Type

Example:

# Pagination: skip first 10, take next 10
g.v().out("follows").skip(10).limit(10).all()

back

back(tag)

Navigate to a previously tagged position.

Prop

Type

Example:

g.v("alice").tag("start").out("follows").out("likes").back("start").all()

filter

filter(func)

Filter vertices using a lambda.

Prop

Type

Examples:

g.v().filter(lambda v: "user" in v).all()
g.v().filter(lambda v: v.isdigit() and int(v) > 100).all()

scan

scan(limit=10, scan_type='v')

Scan nodes ('v') or edges ('e').

Prop

Type

Examples:

g.scan(10, 'v')  # Scan first 10 vertices
g.scan(5, 'e')   # Scan first 5 edges

tag

tag(tag_names)

Capture vertex IDs at this point. Used by view().

Prop

Type

Examples:

g.v("bob").out().tag("friend").all()
g.v("bob").tag("start").out("follows").tag("middle").out().tag("end").all()

view

view(view_name, js_src="...")

Create HTML visualization. Saves to {cog_home}/views/{view_name}.html.

Prop

Type

Example:

view = g.v("bob").out().tag("from").inc().tag("to").view("bob_network")
print(view.url)

render

render(height=700, width=700)

Display visualization in Jupyter notebooks.

Prop

Type

Examples:

g.v("alice").out("follows").tag("friend").view("alice_friends").render()
g.v("alice").out("follows").view("large_view").render(height=800, width=1200)

has

has(predicates, vertex)

Filter vertices with matching outgoing edges.

Prop

Type

Examples:

g.v().has("follows", "fred").all()
g.v().has("status", "cool_person").all()

count

count()

Count vertices. Terminal function.

Examples:

g.v("alice").out("follows").count()  # → 3
g.v().out("status").count()          # → 5

all

all(options=None)

Return all vertices.

Prop

Type

Examples:

g.v("bob").out().all()
# → {'result': [{'id': 'fred'}, {'id': 'cool_person'}]}

g.v("bob").out().all('e')  # Include edges
# → {'result': [{'id': 'fred', 'edges': ['follows']}]}

graph

graph()

Return the full traversal as a graph structure with deduplicated nodes and edges, ready for visualization with D3.js or vis.js. Terminal function.

Example:

g = Graph("social")
g.put("alice", "follows", "bob")
g.put("bob", "follows", "charlie")

g.v("alice").out("follows").out("follows").graph()
# → {
#     "nodes": [
#       {"id": "alice"},
#       {"id": "bob"},
#       {"id": "charlie"}
#     ],
#     "links": [
#       {"source": "alice", "target": "bob", "label": "follows"},
#       {"source": "bob", "target": "charlie", "label": "follows"}
#     ]
#   }

Unlike all() which returns a flat list of vertex IDs, graph() returns both nodes and edges with labels, making it ideal for feeding directly into graph visualization libraries.


lsv

lsv()

List saved view names.


getv

getv(view_name)

Load a saved view.

Prop

Type

Example:

view = g.getv("bob_network")
view.render()

load_csv

load_csv(csv_path, id_column_name, graph_name=None)

Load a CSV file into the graph.

Prop

Type

Examples:

# Load CSV with "user_id" as the identifier
g.load_csv("/path/to/users.csv", "user_id")

# Load into a specific graph name
g.load_csv("/path/to/users.csv", "user_id", "user_graph")

load_triples

load_triples(graph_data_path, graph_name=None)

Load triples from a file (N-Triples or N-Quads).

Prop

Type

Examples:

g.load_triples("/path/to/data.nq")
g.load_triples("/path/to/data.nq", "social_graph")

load_edgelist

load_edgelist(edgelist_path, graph_name=None)

Load an edge list file into the graph.

Prop

Type

Example:

g.load_edgelist("/path/to/edges.txt")

Embedding Methods

CogDB supports storing and querying word/vertex embeddings for similarity search.

put_embedding

put_embedding(word, embedding)

Store an embedding vector for a word/vertex.

Prop

Type

Example:

g.put_embedding("machine_learning", [0.1, 0.2, 0.3, ...])

put_embeddings_batch

put_embeddings_batch(word_embedding_pairs)

Bulk insert multiple embeddings efficiently.

Prop

Type

Example:

g.put_embeddings_batch([
    ("apple", [0.1, 0.2, 0.3]),
    ("orange", [0.2, 0.3, 0.4]),
    ("banana", [0.15, 0.25, 0.35])
])

get_embedding

get_embedding(word)

Retrieve an embedding vector.

Prop

Type

Example:

embedding = g.get_embedding("machine_learning")
# → [0.1, 0.2, 0.3, ...]

delete_embedding

delete_embedding(word)

Remove an embedding.

Prop

Type

Example:

g.delete_embedding("outdated_term")

sim

sim(word, operator, threshold, strict=False)

Filter vertices by cosine similarity to a word.

ParameterDescription
wordWord to compare against
operator"=", ">", "<", ">=", "<=", or "in"
thresholdFloat value, or list of 2 floats for "in" operator
strictIf True, raise error for missing embeddings

Examples:

# Find vertices with similarity > 0.8
g.v().sim("machine_learning", ">", 0.8).all()

# Find vertices with similarity in range
g.v().sim("machine_learning", "in", [0.5, 0.9]).all()

k_nearest

k_nearest(word, k=10)

Find the k vertices most similar to the given word.

Prop

Type

Example:

g.v().k_nearest("machine_learning", k=5).all()

Network Methods

serve

serve(port=8080, host="0.0.0.0", blocking=False, writable=False, share=False)

Start HTTP server for this graph instance.

Examples:

# Basic server
g.serve(port=8080)

# Allow write operations
g.serve(port=8080, writable=True)

# Share publicly via CogDB relay
g.serve(port=8080, share=True)
print(g.share_url())  # https://abc123.s.cogdb.io/

stop

stop()

Stop serving this graph.

Example:

g.stop()

connect (class method)

Graph.connect(url, timeout=30)

Connect to a remote CogDB server.

Prop

Type

Example:

remote = Graph.connect("http://192.168.1.5:8080/social")
remote.v("alice").out("knows").all()

Complete Example

Example:

from cog.torque import Graph, ASC, DESC

# Create graph
g = Graph("social_network")

# Add data
g.put_batch([
    ("alice", "follows", "bob"),
    ("bob", "follows", "charlie"),
    ("charlie", "follows", "alice"),
    ("alice", "status", "active"),
    ("bob", "status", "active"),
    ("charlie", "status", "inactive")
])

# Query: Find who alice follows
g.v("alice").out("follows").all()
# → {'result': [{'id': 'bob'}]}

# Query: Find followers of bob, ordered
g.v("bob").inc("follows").order(ASC).all()
# → {'result': [{'id': 'alice'}]}

# Query: Complex traversal with tags
g.v("alice").tag("start").out("follows").tag("middle").out("follows").tag("end").all()
# → {'result': [{'start': 'alice', 'middle': 'bob', 'end': 'charlie', 'id': 'charlie'}]}

# Query: Find active users
g.v().has("status", "active").all()
# → {'result': [{'id': 'alice'}, {'id': 'bob'}]}

# Get graph structure for visualization
g.v("alice").out("follows").out("follows").graph()
# → {'nodes': [{'id': 'alice'}, ...], 'links': [{'source': 'alice', 'target': 'bob', 'label': 'follows'}, ...]}

# Remove a specific edge
g.delete("alice", "status", "active")

# Clear all data (graph remains reusable)
g.truncate()

# Close when done
g.close()

On this page