Python Embedded

Run Traverse inside your Python process, with no server: open or create a .tvdb file, query it with openCypher or GQL, and load data with the bulk writer.

Install

pip install traverse-embedded

Note: the distribution is named traverse-embedded; the import name is traverse. It ships prebuilt wheels for Windows x64 and Linux x64 (manylinux2014), one abi3 wheel per platform for every Python 3.10 and newer. The engine runs in your process.

On other platforms, build a wheel from the source with maturin (it needs a Rust toolchain):

pip install maturin
cd crates/traverse-python
maturin build --release
pip install ../../target/wheels/traverse_embedded-*.whl

Open a Database

import traverse

# open, or create, a database file
db = traverse.open("mydb.tvdb")
db.close()

# or as a context manager: closed (and saved) at the end of the block
with traverse.open("mydb.tvdb") as db:
    pass

Closing rolls back transactions still open on the database, saves it, and leaves the .tvdb as a single file. Another process can't open the file while it's open.

Run Queries

execute on the database runs a query as a transaction of its own: a read runs on a snapshot and never waits, a write commits when it succeeds and rolls back when it fails.

with traverse.open("mydb.tvdb") as db:
    db.execute("CREATE (:Person {name: 'Alice', age: 30}), (:Person {name: 'Bob', age: 25})")

    result = db.execute("MATCH (n:Person) WHERE n.age > $min_age RETURN n.name AS name", {"min_age": 26})
    for row in result:
        print(row["name"])  # Alice

GQL

Pass dialect="gql" to run ISO/IEC 39075 GQL instead of openCypher:

with traverse.open("mydb.tvdb") as db:
    for row in db.execute("MATCH (n:Person) FILTER n.age > 26 RETURN n.name AS name", dialect="gql"):
        print(row["name"])  # Alice

Transactions

with traverse.open("mydb.tvdb") as db:
    # a write transaction: commits on a clean exit, rolls back on an exception
    with db.begin() as tx:
        tx.execute("CREATE (:Person {name: 'Carol', age: 41})")
        tx.execute("MATCH (a:Person {name: 'Alice'}), (c:Person {name: 'Carol'}) CREATE (a)-[:KNOWS]->(c)")

    # a read transaction: a snapshot of the database as of now, alongside the writer and other readers
    with db.begin_read() as snapshot:
        print(snapshot.execute("MATCH (p:Person) RETURN count(p) AS n").data())  # [{'n': 3}]

You can also call commit() and abort() yourself; dropping an uncommitted transaction rolls it back. One write transaction is active at a time: begin waits for the active one for up to db.busy_timeout seconds (default 5), then raises traverse.BusyError. A statement that fails after changing data fails its transaction: later statements and commit raise, and only a rollback ends it.

A commit is durable when it returns: it's written to the database's redo log first. The database also saves itself in the background (once the log has grown by 64 MiB, or when a commit has gone five minutes unsaved), so reopening after a crash replays little.

QueryResult

with traverse.open("mydb.tvdb") as db:
    result = db.execute("MATCH (n:Person) RETURN n.name, n.age")
    print(result.columns)    # ['n.name', 'n.age']
    print(result.row_count)  # 3

    for row in result:       # each row is a dict
        print(row["n.name"])

    rows = result.data()     # all rows as a list of dicts
    rows = result.values()   # all rows as a list of tuples, in column order

    result = db.execute("CREATE (n:Test)")
    print(result.stats)      # {'nodes_created': 1, 'labels_added': 1}

values() is the cheapest way to read a whole result: the rows come back in column order without a dict per row. Iterating the result or calling data() gives dicts, which share their keys across rows.

Bulk Writer

A bulk load is a write transaction that skips the redo log: commit saves the database with the load in it, so the data is written once and is durable when commit returns. Readers don't see the load until then, and abort (or an exception in the with block) rolls it back.

with traverse.open("registry.tvdb") as db:
    with db.bulk_writer() as writer:
        acme = writer.create_node(["Company"], {"name": "Acme", "founded": 1998})
        globex = writer.create_node(["Company"], {"name": "Globex", "founded": 2004})
        writer.create_edge(acme, globex, "OWNS", {"share": 0.6})

A file built this way can be uploaded to a Traverse server and put behind an alias, so queries move to the new data in one step.

Indexes

with traverse.open("registry.tvdb") as db:
    # in a bulk load
    with db.bulk_writer() as writer:
        writer.create_index("company_name", "Company", "name")
        writer.create_edge_index("owns_share", "OWNS", "share")
        writer.create_edge_index("owns", "OWNS")  # type-only index

    # or with Cypher
    db.execute("CREATE INDEX company_founded FOR (c:Company) ON (c.founded)")

Timeouts, Cancelling and Errors

with traverse.open("mydb.tvdb") as db:
    db.busy_timeout = 10       # seconds to wait for another writer
    db.statement_timeout = 30  # seconds a statement may run (None: no limit)
    try:
        db.execute("MATCH (p:Person) RETURN nosuchfunction(p.name)")
    except traverse.TraverseError as e:
        print(e.gql_status)    # 42N48 (unknown function)

A statement that runs past statement_timeout, or that another thread stops with Transaction.cancel(), raises traverse.QueryInterruptedError. Every error is a traverse.TraverseError, with its GQLSTATUS code in gql_status (the ISO/IEC 39075 code where the standard has one). Embedded transactions show in SHOW TRANSACTIONS, and TERMINATE TRANSACTIONS stops them.

Flush and Close

db = traverse.open("mydb.tvdb")
db.flush()  # save now (waits for an active writer like begin)
db.close()  # roll back open transactions, save, release the file