Query and Mutate with Cypher

Use Cypher when the task is a graph pattern or a row pipeline rather than one known-ID lookup. GraphDB.query returns QueryResult with columns and records; iteration yields row dictionaries. Parameters supply values without interpolating them into query text. See Choose How to Load and Query Data for direct lookup and loading alternatives, and Cypher Queries for the detailed supported syntax.

Read a pattern and aggregate its rows

Standalone runnable example. Install gestaltdb[lmdb]. This small graph has two drugs and two proteins. The pattern binds a drug, a directed binds edge, and its protein endpoint; WHERE filters the bound rows.

Aspirin binds PTGS1 with score 0.9 and PTGS2 with score 0.7; Ibuprofen binds PTGS1 with score 0.95.

The tutorial’s stored graph, generated by visualize_nodes_edges. All three edges are shown; the first query below selects only Aspirin’s PTGS1 target when the minimum score is 0.8.

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

Ordinary read/aggregate queries support these choices; automatic read pinning remains backend-qualified.

1python -m pip install "gestaltdb[lmdb]"
 1from tempfile import TemporaryDirectory
 2from gestaltdb.graphdb import Edge, GraphDB, Node
 3
 4with TemporaryDirectory() as root:
 5    with GraphDB.create(f"{root}/graph", backend='lmdb', serializer='json') as graph:
 6        graph.put_nodes([
 7            Node("d1", labels=["Drug"], properties={"name": "Aspirin"}),
 8            Node("d2", labels=["Drug"], properties={"name": "Ibuprofen"}),
 9            Node("p1", labels=["Protein"], properties={"name": "PTGS1"}),
10            Node("p2", labels=["Protein"], properties={"name": "PTGS2"}),
11        ])
12        graph.put_edges_bulk([
13            Edge("e1", "d1", "p1", properties={"type": "binds", "score": 0.9}),
14            Edge("e2", "d1", "p2", properties={"type": "binds", "score": 0.7}),
15            Edge("e3", "d2", "p1", properties={"type": "binds", "score": 0.95}),
16        ])
17        graph.create_node_property_index("name")
18        hits = graph.query(
19            "MATCH (d:Drug {name: $name})-[r:binds]->(p:Protein) "
20            "WHERE r.score >= $minimum RETURN p.name AS protein",
21            parameters={"name": "Aspirin", "minimum": 0.8},
22        )
23        assert hits.columns == ("protein",)
24        assert hits.records == [{"protein": "PTGS1"}]
25
26        counts = graph.query(
27            "MATCH (d:Drug)-[r:binds]->(p:Protein) WHERE r.score >= $minimum "
28            "WITH d.name AS drug, count(p) AS targets "
29            "RETURN drug, targets ORDER BY drug",
30            parameters={"minimum": 0.8},
31        )
32        assert counts.records == [
33            {"drug": "Aspirin", "targets": 1},
34            {"drug": "Ibuprofen", "targets": 1},
35        ]

Read the relationship pattern as a conjunction: a matching drug and an outgoing edge of type binds and a matching protein. This is a physical property-graph match, not a Datalog rule that publishes new conclusions. Parallel edges may produce separate rows. Use DISTINCT explicitly when distinct logical values, rather than relationship occurrences, are intended.

WITH replaces the available variable scope with its projections. Here it groups by the non-aggregate drug output and computes a count per group. ORDER BY makes the expected row order explicit. Property indexes can accelerate eligible entry predicates; a computed expression or arbitrary join need not use every applicable index. See Property-Graph Filtering and Indexes for setup and freshness.

Write, constrain, and inspect

Standalone runnable example. Requires gestaltdb[lmdb]. It creates a single-property uniqueness constraint, writes one node, and updates it using a parameterized match. The explicit transaction groups the two data queries.

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

This example requires an explicit graph-wide transaction. LevelDB and plain PyRex are intentionally not offered.

1python -m pip install "gestaltdb[lmdb]"
 1from tempfile import TemporaryDirectory
 2from gestaltdb.graphdb import GraphDB
 3
 4with TemporaryDirectory() as root:
 5    with GraphDB.create(f"{root}/graph", backend='lmdb', serializer='json') as graph:
 6        graph.query("CREATE CONSTRAINT drug_name FOR (d:Drug) REQUIRE d.name IS UNIQUE")
 7        with graph.transaction() as tx:
 8            tx.query("CREATE (d:Drug {id: $id, name: $name}) RETURN d.id AS id",
 9                     parameters={"id": "d1", "name": "Aspirin"})
10            changed = tx.query(
11                "MATCH (d:Drug {name: $name}) SET d.approved = true "
12                "RETURN d.approved AS approved",
13                parameters={"name": "Aspirin"},
14            )
15            assert changed.records == [{"approved": True}]
16        assert graph.get_node("d1").properties["approved"] is True
17        assert len(graph.query("SHOW CONSTRAINTS").records) == 1
18        graph.create_node_property_index("name")
19        assert graph.query("SHOW INDEXES").records

CREATE generates fresh IDs unless supplied as shown. MERGE provides an explicit match-or-create operation; it is not the same as always creating a new node. Other supported write forms include SET, REMOVE, DELETE / DETACH DELETE and FOREACH. See Cypher Queries for exact syntax and scope.

Constraints currently cover single-property node uniqueness and required values on Cypher writes, not universal validation of direct object writes. Transaction guarantees depend on the selected backend; the LMDB example is not a promise of graph-wide transactions on LevelDB or plain PyRex (Storage Backends). Source read snapshots do not make writes atomic across an arbitrary application workflow.

Temporal scalar values versus historical queries

Standalone runnable example. Requires gestaltdb[lmdb]. A temporal scalar constructor creates a property/expression value. A valid-time qualifier selects immutable version history, not the mutable current graph.

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

Temporal-version payloads use the selected codec. Historical selection is separate from current mutable snapshots.

1python -m pip install "gestaltdb[lmdb]"
 1from tempfile import TemporaryDirectory
 2from gestaltdb.graphdb import GraphDB, Node
 3
 4with TemporaryDirectory() as root:
 5    with GraphDB.create(f"{root}/graph", backend='lmdb', serializer='json') as graph:
 6        scalar = graph.query(
 7            "UNWIND [1] AS seed RETURN date($day) AS day",
 8            parameters={"day": "2024-01-02"},
 9        )
10        assert scalar.records[0]["day"].value.isoformat() == "2024-01-02"
11        graph.temporal.put_node_version(
12            Node("d1", labels=["Drug"], properties={"name": "Aspirin"}), valid=(0, 10),
13        )
14        historical = graph.query(
15            "MATCH (d:Drug) FOR VALID_TIME AS OF datetime($at) RETURN d.name AS name",
16            parameters={"at": "1970-01-01T00:00:00.000005Z"},
17        )
18        assert historical.records == [{"name": "Aspirin"}]
19        assert graph.get_node("d1") is None  # version writes are separate

The version-write integers are UTC-microsecond valid-time instants, not day numbers. The query qualifier must evaluate to a datetime()/TemporalInstant value; a bare integer is not a valid Cypher qualifier. Add FOR SYSTEM_TIME AS OF to select a recorded-history horizon under the bitemporal contract. Qualified queries are read-only and their context is query-wide; see the timeline in Temporal and bitemporal data, the shared-horizon workflow in Read one historical account consistently and the temporal section of Cypher Queries. Neither a scalar constructor nor a historical MATCH runs interval Datalog (Reason over complete validity ranges).

Capability map and boundaries

Progress from the tutorial to the reference

Need

Supported route

Boundary

Explore paths

Fixed/variable-length and shortest paths, path bindings and accessors

Trail and shortest-path semantics are explicit; not GQL quantified paths.

Compose results

Chained MATCH, OPTIONAL MATCH, WITH, UNWIND, UNION and correlated CALL

Clause-local filtering, nulls and variable scope matter.

Compute values

Documented scalar/temporal functions, expressions and aggregates

No arbitrary Python dispatch or unrestricted function catalogue.

Inspect schema

SHOW INDEXES, SHOW CONSTRAINTS; node constraints

No relationship/multi-property constraints or direct-write enforcement.

Call a procedure

pg.sample_typed_paths and kg.entails

Only registered names/fields execute; kg.entails is bounded.

Read inferred facts

Explicit generation-pinned Generation-pinned reasoning-aware Cypher

Smaller read-only projection, not automatic inference in ordinary Cypher.

Pattern comprehensions, pattern arguments to exists(), unregistered procedures and unrestricted Cypher/GQL compatibility are not supported. Syntax/semantic errors are source-located ValueError subclasses. Read-only queries automatically pin current state where supported; read_snapshot=True requires that guarantee and fails on unsupported backends. Refer to Cypher Queries for the complete documented subset and Storage Backends for backend-qualified behavior.