Skip to main content

HelixDB Python SDK

The Python SDK pairs an idiomatic query-builder DSL with synchronous and asynchronous clients for sending HelixDB queries to POST /v2/query or executing them against an embedded database. The async client uses HTTPX; the sync API remains unchanged.

License

The HelixDB Python SDK is licensed under the Apache License 2.0. See LICENSE for the complete terms.

from helixdb import Client, Predicate, g, read_batch

query = (
    read_batch()
    .var_as(
        "users",
        g()
        .n_with_label("User")
        .where(Predicate.eq("status", "active"))
        .limit(25)
        .value_map(["$id", "name", "status"]),
    )
    .returning(["users"])
)

request = query.to_query_request()
result = Client("http://localhost:6969").query(request)

Async Client

Reuse one AsyncClient so its HTTPX connection pool can serve many requests. There is no timeout unless you configure one on the client or request.

import asyncio

import httpx

from helixdb import AsyncClient

async def main():
    limits = httpx.Limits(max_connections=20, max_keepalive_connections=10)
    async with AsyncClient(timeout=10.0, limits=limits) as client:
        first, second = await asyncio.gather(
            client.query(request),
            client.execute(request, writer_only=True, timeout=2.0),
        )
        return first, second

results = asyncio.run(main())

AsyncClient, AsyncQueryBuilder, and AsyncQueryExecutionRequest are also exported from the compatibility import path helix_db. Builder methods preserve the synchronous writer, warm, durability, authorization, and response contracts.

HTTP cancellation propagates as asyncio.CancelledError; the response stream is closed and the client remains reusable. For embedded operations, use asyncio.timeout(...) when a cancellation boundary is required. HTTPX AsyncBaseTransport instances can be injected for custom networking or tests; the client owns and closes an injected transport. Calling await client.close() more than once is safe.

HelixError.code preserves the static server or embedded code separately from the readable details. See the canonical query error-code reference for the complete catalog and migration contract.

Warm a read with client.execute(request, warm_only=True). Helix Cloud fans the ordinary read out to every eligible backend, discards the results, and returns an empty successful response after at least one target succeeds. Pass writer_only=True as well to warm only the authoritative writer. Warm writes return an error before backend execution. A standalone local warm read can return its normal query payload instead.

Database ID

Helix Cloud gateways require an x-helix-database-id header on every query route, native and Cypher, and reject requests without it with tenant_id_required. Pass database_id when you construct a server client, or set it later with with_database_id(...). Call with_database_id() with no argument to clear it.

from helixdb import AsyncClient, Client

client = Client("https://helix.example.com", api_key=api_key, database_id="db_123")
client.with_database_id("db_456")  # later requests target another database

async_client = AsyncClient.server(
    "https://helix.example.com", api_key=api_key, database_id="db_123"
)

Builders and prepared requests keep the database ID that was set when they were created. Embedded clients ignore it.

The DSL emits the same query JSON AST as the Rust, TypeScript, and Go SDKs. Python methods use snake_case; compatibility aliases such as nWithLabel and valueMap are also available for users translating TypeScript examples directly.

Query Parameters

from helixdb import Predicate, define_params, g, param, read_batch

params = define_params({
    "tenant_id": param.string(),
    "limit": param.i64(),
})

query = (
    read_batch()
    .var_as(
        "users",
        g()
        .n_with_label("User")
        .where(Predicate.eq("tenantId", params.tenant_id))
        .limit(params.limit)
        .value_map(["$id", "name", "tenantId"]),
    )
    .returning(["users"])
)

body = query.to_query_json(
    params,
    {"tenant_id": "acme", "limit": 10},
    query_name="find_users",
)

Use text_search(...) after a node or edge traversal to rank only the IDs in that current stream. This is an exact BM25 prefilter: results equal an exhaustive search of the selected tenant partition, intersected with the unique input IDs, followed by deterministic top-k selection.

BM25 statistics still come from the full tenant partition.

from helixdb import (
    Predicate,
    PropertyProjection,
    define_params,
    g,
    param,
    read_batch,
)

search_params = define_params({
    "tenant_id": param.string(),
    "query": param.string(),
    "limit": param.i64(),
})

query = (
    read_batch()
    .var_as(
        "documents",
        g()
        .n_with_label("Document")
        .where(Predicate.eq("tenantId", search_params.tenant_id))
        .text_search_with(
            "Document",
            "body",
            search_params.query,
            search_params.limit,
            search_params.tenant_id,
        )
        .project([
            PropertyProjection.renamed("$id", "id"),
            PropertyProjection.renamed("$score", "score"),
            PropertyProjection.new("title"),
        ]),
    )
    .returning(["documents"])
)

Use the literal form as .text_search("Document", "body", "graph databases", 10, "acme"). The same methods work on edge streams. Source-level text_search_nodes[_with] and text_search_edges[_with] remain whole-partition searches.

Restricted results contain unique input IDs, return at most k, and order by $score descending then entity ID ascending. The selected input row keeps its bindings, path, and sack. An empty input returns without opening the text index. A non-node/edge stream or more than 1,000,000 unique candidates is a query error. For a tenant-scoped index, pass the same tenant partition used to build the candidate stream.

Row Bindings

Use bind(...) when a multi-hop traversal needs to keep earlier elements correlated with later results. project_distinct_bindings(...) emits one row per projected tuple.

from helixdb import BindingProjection, g, read_batch, sub

query = (
    read_batch()
    .var_as(
        "workloads",
        g()
        .n_with_label("Service")
        .bind("service")
        .optional(sub().in_("CREATES").bind("deployment"))
        .union([sub().in_("MANAGES").bind("owner"), sub().out("ROUTES_TO").bind("workload")])
        .project_distinct_bindings([
            BindingProjection.binding("service", "$id", "service_id"),
            BindingProjection.coalesce(
                [
                    BindingProjection.binding_ref("deployment", "$id"),
                    BindingProjection.binding_ref("owner", "$id"),
                    BindingProjection.binding_ref("workload", "$id"),
                ],
                "workload_id",
            ),
        ]),
    )
    .returning(["workloads"])
)

Embedded Client

Install the SDK and matching native runtime:

python -m pip install helix-db helix-db-embedded
from helixdb import Client, InMemory

client = Client.embedded(InMemory("app"))
try:
    response = client.query(request)
finally:
    client.close()

Cache profiles are fixed when the handle opens. Vector-memory-only mode disables SlateDB and object-store caches, not canonical persistence.

from helixdb import EmbeddedCacheConfig, VectorMemoryOnly

client = Client.embedded(
    InMemory("app"),
    cache=EmbeddedCacheConfig(256 * 1024 * 1024, VectorMemoryOnly()),
)

Client.embedded_reader(...) opens an existing disk or object-storage database read-only. Stored routes and query bundles are not supported.

The async client awaits native UniFFI operations directly and supports the same writer, reader, memory, disk, object-storage, and cache configurations.

from helixdb import AsyncClient, Disk, InMemory

async def embedded_query(request):
    writer = await AsyncClient.embedded(InMemory("app"))
    async with writer:
        return await writer.query(request)

async def read_checkpoint(request):
    reader = await AsyncClient.embedded_reader(Disk("./data", "app"))
    async with reader:
        return await reader.query(request)

Concurrent asyncio.gather(...) calls are passed to the native runtime without a synchronous wrapper. Native graph loading remains available only on Client.

Native graph algorithms

from helixdb import Client, SourcePredicate, g
from helixdb.graph import BetweennessOptions, GraphSelection

client = Client()
selection = GraphSelection(
    node_traversal=g().n_where(SourcePredicate.has_key("$id")),
    edge_traversal=g().e_where(SourcePredicate.has_key("$id")),
    direction="directed",
    allow_full_scan=True,
)
graph = client.graph(selection)
scores = graph.betweenness_centrality(BetweennessOptions.graphify_default())

The returned object retains the immutable Rust topology. Every accessor and algorithm runs locally without another Helix read. Native wheels are required for this graph API and embedded mode; server clients do not require the native runtime.

Run the SDK tests from the repository root:

python -m pip install -e './sdks/python[dev]'
python -c 'import doctest, helixdb.async_client as module; raise SystemExit(doctest.testmod(module).failed)'
python -m unittest discover -s sdks/python/tests

Cypher

Clients built from this checkout expose additive Cypher methods for HTTP and embedded connections. cypher(...) executes one statement through POST /v2/cypher. explain_cypher(...) plans the same request through POST /v2/cypher/explain without executing it and returns the explain object.

from helixdb import Client

client = Client(api_key=api_key, database_id="db_123")
rows = client.cypher(
    "MATCH (p:Person) WHERE p.age >= $age RETURN p.name AS name",
    {"age": 30},
    query_name="adults",
)
plan = client.explain_cypher(
    "MATCH (p:Person) WHERE p.age >= $age RETURN p.name AS name",
    {"age": 30},
)
client.cypher(
    "CREATE (:Person {name: $name})",
    {"name": "Ada"},
    writer_only=True,
    await_durability=True,
)

Both methods accept the routing options that execute accepts: writer_only, warm_only (reads only), and await_durability (writes only). Helix Cloud answers a successful warm request with 204 No Content; cypher then returns {"columns": [], "rows": []} and explain_cypher returns None. timeout defaults to 30 seconds on Client and to the client timeout on AsyncClient, whose methods have the same signatures and are awaited.

Embedded clients reject routing options with an InvalidRequest error. Embedded explain needs native bindings that expose explain_cypher_json. Older builds raise HelixError with kind EmbeddedUnavailable.

See the Cypher guide for the language profile, parameters, lossless values, and transaction behavior. Native DSL query methods keep their existing contract.

SQL

sql(...) translates one SQL statement to Cypher and runs it through POST /v2/sql; explain_sql(...) plans it through POST /v2/sql/explain. A list or tuple of parameters binds each ? in order; a dictionary binds :name, $name and @name. mappings renames tables and join columns.

rows = client.sql(
    "SELECT u.name AS name FROM people u WHERE u.age >= ?",
    [30],
    mappings={"tables": {"people": "User"}},
    query_name="adults",
)
plan = client.explain_sql("INSERT INTO User (name) VALUES (:name)", {"name": "Ada"})

Both take the routing options, timeout, and embedded behavior of the Cypher methods. See the SQL guide.

Metadata

Release files for helix-db 0.4.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for helix-db 0.4.0
File Size Uploaded Provenance Actions
helix_db-0.4.0.tar.gz 75.9 kB Without provenance Details for helix_db-0.4.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for helix-db 0.4.0
File Interpreter ABI Platform Actions
helix_db-0.4.0-py3-none-any.whl Python 3 none any Details for helix_db-0.4.0-py3-none-any.whl

Total release size: 132.6 kB

Release files / helix_db-0.4.0.tar.gz

Download URL helix_db-0.4.0.tar.gz
Size 75.9 kB
Tags Source
SHA-256 checksum
How to use checksums
e1d3b06bf52ecda42a16012d57aab7aa51c529d680538c2969c61a7ef345a263
BLAKE2b-256 checksum
How to use checksums
5ceecd2c52056f4a80267faf2b03a22d9b9c92e69a78635fbd82b1539d401db3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.3

Release files / helix_db-0.4.0-py3-none-any.whl

Download URL helix_db-0.4.0-py3-none-any.whl
Size 56.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
184e20f4c0d9634b9107d51b94a5d05f1c321789076cd5d98122590474275957
BLAKE2b-256 checksum
How to use checksums
81e5254bc16cdca8b6cc98d8ee3bd64c8f03fa4a03093b27e47f617d851272d3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.3

Security for helix-db 0.4.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page