TuringDB Python SDK
The TuringDB Python SDK provides an easy interface for connecting to your local TuringDB server, running queries, and managing graphs programmatically.
Install the PythonSDK:
Using uv package manager (you will need to create a project first):
uv add turingdbor using pip:
pip install turingdbThe SDK targets TuringDB v3: pin turingdb>=3.1 in your project (older projects may pin 1.x, which uses the previous engine and a much smaller Cypher subset). Upgrade the SDK and the server together: a 3.1 SDK speaks the binary protocol of a 3.1 server. The wheel supports Python 3.10 to 3.14 on Linux (x86_64, aarch64) and macOS 15 or later (arm64). It also contains the turingdb command-line tool, the turing-parquet import tool, and the in-process engine.
Getting Started
from turingdb import TuringDB
# Connect to a server running on this machine (localhost:6666)
client = TuringDB()
# or name the host and the port
client = TuringDB(host="localhost", port=6666)
# List the graphs on disk
print(client.list_available_graphs())Client backends
TuringDB(...) is a facade over two interchangeable backends, chosen with the type argument:
type | Runs against | Constructor arguments |
|---|---|---|
"native" (default) | A running TuringDB server, over TuringDB’s binary protocol | host="localhost", port=6666, optional token |
"embedded" | An in-process engine, with no server or socket | data_dir="/path/to/.turing" |
# A running server (the default)
client = TuringDB(host="localhost", port=6666)
# Embedded, in-process: no server needed
client = TuringDB(type="embedded", data_dir="/home/me/.turing")Use a server unless you have a reason not to. Choose embedded when you want a self-contained engine with no server to start, stop or connect to.
Connecting to a server
hostis a host name or an IP address, andporta number (default6666). A URL such as"http://localhost:6666"is refused:host must be a host name or IP address, not a URL.- The client connects as soon as it is created. If no server is listening it raises
TuringDBException: Failed to connect to localhost:6666: Connection refused. - The client sends the graph, change and commit it is set to with every query, so the server keeps no session for it.
- The query API is identical on both backends, and results come back as the same DataFrames.
Authentication
A server started with -auth-on requires a bearer token. Pass it with token= or set the TURINGDB_AUTH_TOKEN environment variable, which the SDK reads automatically:
TURINGDB_AUTH_TOKEN=s3cret turingdb start -demon -auth-onclient = TuringDB(host="localhost", port=6666, token="s3cret")A missing or incorrect token raises TuringDBException: Protocol error from server: Unauthorized: missing or invalid authentication token. The embedded backend runs in-process and needs no authentication, so it does not take a token.
The embedded backend
import os
client = TuringDB(
type="embedded", data_dir=os.path.expanduser("~/.turing")
)data_diris the TuringDB root directory (the one that holdsgraphs/,data/andvector/). Omit it to use~/.turing.- Use an absolute path, for example with
os.path.expanduser("~/..."), since a leading~is not expanded. - Writes still persist to disk when you submit a change, so your work survives the process ending.
- The embedded backend is designed for a single process. For the browser visualizer, concurrent access from several processes, the S3 helpers and
token=, use a server.
Core Methods
list_available_graphs() → list[str]
Returns the graphs on disk in the TuringDB data directory, and the graphs in memory (LIST AVAILABLE GRAPHS).
client.list_available_graphs()list_loaded_graphs() → list[str]
Returns the currently loaded graphs in memory.
client.list_loaded_graphs()create_graph(graph_name: str)
Creates a new empty graph with the specified name.
client.create_graph("mygraph")Internally executes
CREATE GRAPH graph_name
load_graph(graph_name: str, raise_if_loaded: bool = True)
Loads a previously created graph into memory.
client.load_graph("mygraph")If raise_if_loaded=False, it will silently continue if the graph is already loaded.
query(query: str, query_parameters: dict | None = None) → pandas.DataFrame
Runs a Cypher query on the current graph.
df = client.query("MATCH (n:Person) RETURN n.name, n.age")
df = client.query(
"MATCH (n:Person) WHERE n.age >= $min RETURN n.name",
{"min": 30},
)
df = client.query(
"MATCH (n:$label) RETURN n.name", {"label": "Person"}
)Returns results as a pandas.DataFrame, with automatic typing and parsing. query_parameters fills the query’s $name parameters, which stand for values, labels and edge types. Parameter values can be:
| Python value | Cypher value |
|---|---|
str, int, float, bool, None | String, Integer (64-bit), Double, Boolean, null |
list, tuple | List |
dict with string keys | Map |
datetime.datetime with a time zone | DateTime |
datetime.timedelta | Duration |
Other values are refused before the query is sent, with a TuringDBException that names the type: a naive datetime (A datetime parameter must carry a timezone: a naive datetime names no instant), a datetime.date, bytes, and numpy scalars and arrays (A parameter cannot hold a Python int64). Convert numpy values with .tolist() or int() first.
query_raw(query: str, query_parameters: dict | None = None) → dict
Like query, but returns the columns without building a DataFrame: {"data": {column: values}, "dtypes": {column: type name}, "time": milliseconds}. Each values is a numpy array, or a list for strings, nullable columns, lists and maps.
get_graph() → str / set_graph(graph_name: str)
Get or set the active graph for subsequent queries.
is_graph_loaded() → bool
Returns whether the current graph is loaded in memory.
new_change() → int
Creates a new isolated change (equivalent to CHANGE NEW), makes it the active change, and returns its integer ID. The client is already on the new change, so a separate checkout(change=...) is not needed.
change = client.new_change()new_change() raises if the client is already on a change or on a past commit. Call client.checkout() first.
Submit a change by running client.query("CHANGE SUBMIT"), then call client.checkout() to return to main. The client points at the submitted change until you do, so call checkout() before the next query.
Version Control Helpers
TuringDB supports snapshot isolation and versioned commits.
Use the following helpers to navigate graph history or work in isolated changes:
checkout(change: int | str = "main", commit: str = "HEAD")
Switches the working context to a specific change or commit. Checking out a past commit loads it into memory first (LOAD COMMIT).
client.checkout(change=2, commit="abc123")
client.checkout("main") # Reset to defaultchange: change ID or"main"commit: commit hash or"HEAD"
set_commit(commit: str)
Manually set the commit hash to use. Unlike checkout(), it does not load the commit, so run LOAD COMMIT '<hash>' first if it is not in memory.
client.set_commit("haax42")set_change(change: int | str)
Manually set the change ID to use (accepts the int that new_change() returns, or the same number as a string).
client.set_change(3)set_graph(graph_name: str)
Change the current graph context.
client.set_graph("another_graph")You can also read the current context through the current_graph, current_commit (default "HEAD"), and current_change (default "main") properties.
Connection & Timing Helpers
reconnect()
Closes the connection to the server and opens a new one. The client returns to the default graph, main and the latest commit, so set the graph again afterwards. A no-op for the embedded backend.
client.reconnect()
client.set_graph("mygraph")try_reach(timeout: float = 5) / warmup(timeout: float = 5)
Probe connectivity (try_reach) or warm the connection with a lightweight query (warmup). Both raise TuringDBException when the server does not answer within timeout seconds.
get_query_exec_time() → float | None / get_total_exec_time() → float | None
Return the server-side execution time and the full round-trip time (in milliseconds) of the last query.
S3 / Data Transfer
These helpers move graph data between local paths, S3, and the TuringDB server. They need a server, so they are not available on the embedded backend.
s3_connect(bucket_name, access_key=None, secret_key=None, region=None, use_scratch=True)
Connect an S3 client for transfers. Credentials are optional — if omitted, the machine’s configured AWS credentials are used.
client.s3_connect("my-bucket", region="eu-west-1")transfer(src, dst)
Transfer data between a local path, an s3://… URI, or a turingdb://… path. The direction and mechanism are inferred from the URI schemes.
# S3 → server
client.transfer(
"s3://graphs/data.jsonl", "turingdb://data.jsonl"
)
# local → server (via scratch)
client.transfer("./local.gml", "turingdb://local.gml")The equivalent engine commands (issued directly via query) are S3 CONNECT "<key>" "<secret>" "<region>", S3 PULL "<s3-url>" "<dst>", and S3 PUSH "<src>" "<s3-url>".
Response Format
All queries return a pandas.DataFrame, typed according to the schema:
| Cypher Type | pandas dtype |
|---|---|
String | string |
Int64 | Int64 |
UInt64 | UInt64 |
Double | float64 |
Bool | boolean |
DateTime | datetime64[us, UTC] |
Duration | timedelta64[us] |
List, Map | object (Python list, dict) |
Embedding | object (numpy float32 array) |
Point | object (turingdb.Point) |
Nodes and edges (RETURN n) come back as their internal integer IDs (UInt64), so project the properties you need, or return properties(n) as a dictionary. A named path comes back as a list of IDs, node and edge alternating: [0, 0, 1] is node 0, edge 0, node 1. A DateTime or Duration inside a list or a map comes back as a time-zone-aware datetime.datetime or a datetime.timedelta. Doubles keep their full precision. See Functions and data types for the full table.
turingdb.Point is a named tuple (srid, x, y, z), with z set to None for a 2D point, and a crs property such as 'wgs-84'.
Integer columns hold numpy integers, which an f-string prints as np.int64(5). Convert them with .tolist() or int() before writing them into a query or passing them as parameters.
Error Handling
Query errors raise TuringDBException. The message starts with the error code (PARSE_ERROR, ANALYZE_ERROR, PLAN_ERROR, EXEC_ERROR, GRAPH_NOT_FOUND, CHANGE_NOT_FOUND, COMMIT_NOT_FOUND, COMMIT_NOT_LOADED, …) and points at the offending part of the query, or names the graph, change or commit that was not found.
from turingdb import TuringDB, TuringDBException
try:
client.query("MATCH (n RETURN n")
except TuringDBException as e:
print("Query failed:", e)Connection problems raise TuringDBException too:
Failed to connect to localhost:6666: Connection refusedwhen no server is listening.Protocol error from server: ...when the server refuses a request: a missing or wrong token, or a request over the 1 MiB limit. The server then closes the connection, so callclient.reconnect()and set the graph again before the next query.The query parameters exceed 1048576 byteswhen the parameters alone are over the limit. Nothing is sent, and the connection stays open.
Example Workflow
from turingdb import TuringDB
# Connect to the server running on localhost:6666
client = TuringDB(host="localhost", port=6666)
# Create a new graph called mygraph
client.create_graph("mygraph")
# Set working graph
client.set_graph("mygraph")
# Create a new change on the graph
change = client.new_change()
# Checkout into the change
client.checkout(change=change)
# Multiple nodes and edges can be created at the same time
# using the following syntax
client.query("""
CREATE
(apoe_gene:Gene {name: 'APOE', chromosome: '19',
location: '19q13.32'}),
(apoe_protein:Protein {name: 'Apolipoprotein E',
function: 'Lipid_transport', tissue: 'Brain_and_liver'}),
(alzheimers:Disease {name: 'Alzheimers_Disease',
type: 'Neurodegenerative'}),
(cholesterol:Molecule {name: 'Cholesterol', type: 'Lipid'}),
(apoe_gene)-[:ENCODES]->(apoe_protein),
(apoe_protein)-[:BINDS]->(cholesterol),
(apoe_protein)-[:ASSOCIATED_WITH]->(alzheimers)
""")
# Commit the change
client.query("COMMIT")
client.query("CHANGE SUBMIT")
# Checkout into main
client.checkout()
# Query graph, with the gene name as a parameter
df = client.query(
"MATCH (n:Gene {name: $name}) RETURN n.name, n.chromosome",
{"name": "APOE"},
)
print(df)Notes
- Both backends use a compiled extension that ships in the wheel.
- The SDK supports the full TuringDB Cypher dialect, including matching by internal node ID (
WHERE n = 1234) and versioned queries against past commits.
Need help writing queries? → See the TuringDB Query Cheatsheet
The SDK’s source is in the TuringDB repository on GitHub. To query TuringDB from JavaScript or TypeScript, see the JavaScript SDK.

