Quickstart

Create a graph, select a relationship with Cypher, and reuse a snapshot for sampling. This standalone example uses disposable storage and closes the database even if an operation fails. No database server is needed.

Install one backend

Use a supported Python version (3.10–3.13) and install the LMDB extra for this example:

1python -m pip install "gestaltdb[lmdb]"

The base package has no embedded KV backend. LMDB, LevelDB and PyRex/RocksDB are swappable persistence choices; serializers are selected independently. This example explicitly chooses LMDB and built-in JSON. See Storage Backends and Serializers for other choices and their transaction/snapshot limits.

Create, query, and sample

Standalone runnable example. The query finds a drug’s high-scoring protein target. A property index supports direct name lookup; native labels and relationship types are indexed automatically.

Aspirin has one outgoing binds relationship with score 0.9 to PTGS1.

This example’s two-node graph, drawn with GestaltDB’s own visualize_nodes_edges API. The arrow is the stored relationship, not an inference step.

Standalone example. Choose the capability-qualified installation tab below.

Choose an independently installed backend and codec. The source example uses LMDB/JSON; each tab is a complete alternative. Snapshot builds here do not require a verifiable current snapshot.

1python -m pip install "gestaltdb[lmdb]"
 1from tempfile import TemporaryDirectory
 2
 3from gestaltdb.graphdb import Edge, GraphDB, Node
 4from gestaltdb.sampling import SamplerEngine
 5
 6with TemporaryDirectory() as root:
 7    with GraphDB.create(
 8        f"{root}/graph", backend='lmdb', serializer='json'
 9    ) as graph_db:
10        graph_db.put_nodes([
11            Node("drug-1", labels=["Drug"], properties={"name": "Aspirin"}),
12            Node("protein-1", labels=["Protein"], properties={"name": "PTGS1"}),
13        ])
14        graph_db.put_edge(Edge(
15            "binding-1", "drug-1", "protein-1",
16            properties={"type": "binds", "score": 0.9},
17        ))
18
19        graph_db.create_node_property_index("name")
20        matches = graph_db.nodes_by_property("name", "Aspirin")
21        assert [node.get_id for node in matches] == ["drug-1"]
22
23        result = graph_db.query(
24            "MATCH (d:Drug {name: $name})-[r:binds]->(p:Protein) "
25            "WHERE r.score >= $minimum "
26            "RETURN d.id AS drug, p.name AS protein, r.score AS score",
27            parameters={"name": "Aspirin", "minimum": 0.8},
28        )
29        assert result.records == [
30            {"drug": "drug-1", "protein": "PTGS1", "score": 0.9}
31        ]
32        print(result.records)
33
34        # Build once while the source is open; reuse after it closes.
35        snapshot = graph_db.build_sampler_snapshot(f"{root}/sampler")
36
37    engine = SamplerEngine.load(snapshot.path, mode="memmap", seed=7)
38    sample = engine.sample_neighbors_external(
39        ["drug-1"], fanout=5, relations=["binds"],
40    )
41    assert sample.to_external(engine.snapshot)["neighbor_nodes"].tolist() == [
42        "protein-1"
43    ]
44
45    # create() wrote a manifest: open() recovers the backend and codec.
46    with GraphDB.open(f"{root}/graph") as reopened:
47        assert reopened.get_node("drug-1").properties["name"] == "Aspirin"

The printed result is:

1[{'drug': 'drug-1', 'protein': 'PTGS1', 'score': 0.9}]

What the example establishes

  • Graph model: nodes have stable IDs, labels and properties. Edges have their own IDs, directed endpoints and properties; properties["type"] identifies the relationship type. Multiple distinct edges may connect the same nodes. Mathematically, this is a directed multigraph \(G=(V,E,s,t)\), where \(s,t:E\to V\) map each edge to its source and target; labels/properties attach to those entities.

  • Access choices: use direct reads when you know IDs, explicit indexes for property cohorts, and Cypher for graph patterns and composed results. Cypher supports writes too, but is a documented subset, not every Cypher/GQL feature (Cypher Queries).

  • Index requirements: label/type indexes are automatic; property indexes are explicit. Deferred ingestion requires index rebuilds before index-backed reads (Property-Graph Filtering and Indexes).

  • Persistence: create writes a self-describing database directory; open reuses it. Context managers close handles. The temporary directory here intentionally deletes the demonstration data when the block ends.

  • Sampling: the snapshot is immutable and does not include later graph writes. Array-native sampling needs no open database. _external methods accept application IDs; to_external converts compact output IDs back for inspection. Memmap avoids eager array loading, not all memory use (Graph sampling API and policy reference).

  • Training tasks: continue with Sampling for graph learning for ID domains, eligible-graph filtering and focused layer, subgraph, temporal and negative guides.

Filtering the query’s rows or seeds does not filter every sampled hop. Build a filtered snapshot with node_filter / edge_filter when that is the intended graph; see Property-Graph Filtering and Indexes. This example uses the whole two-node graph.

Choose your next path

From application goal to focused guide

I want to…

Continue with…

Choose persistence, codecs or current-snapshot guarantees

The Property Graph, Storage Backends, Serializers, Compatibility, Migration, and Recovery

Load Arrow/Polars tables or select indexed cohorts

Choose How to Load and Query Data, Load Arrow and Polars Data, Property-Graph Filtering and Indexes

Query paths, aggregate, or mutate with Cypher

Query and Mutate with Cypher, Cypher Queries

Draw layers, subgraphs, walks or temporal negatives

Graph sampling API and policy reference, Random-walk embedding pipelines

Inspect historical state at valid/system time

Temporal and bitemporal data, Append and revise historical records, Read one historical account consistently

Record sourced claims, derive stored rules or inspect belief

Sourced claims and conflicting evidence, Stored rules and support maintenance, Bounded Modal and Epistemic Evaluation, Unified inference audit

Classify entities from ontology axioms

Ontology reasoning

Evaluate standalone binary/typed Datalog

Facts, Rules, and Explanations, Build typed rules step by step, Typed Datalog: literals, filters, aggregates, Scoped closed-world negation

Compute intervals over which conclusions hold

Reason over complete validity ranges, Update and inspect interval-valued conclusions

Connect a graph to reasoning and source-verified saved state

Current-graph ontology adapters, Authenticated durable-session resume

Visualize or exchange results

Explore graphs and reasoning offline, Exchange current graphs with NetworkX and GEXF, Notebook Usage

Ordinary mutable writes do not create temporal history automatically. Ontology compilation and standalone reasoning do not silently change graph records, Cypher results or sampler membership. The Components, Interfaces, and Applications guide explains these separate responsibilities and their explicit adapters.