TuringDB home pagelight logodark logo
  • Discord
  • GitHub
  • Website
TuringDB

Get Started

  • Introduction
  • Get Started
  • Claude Code Skill
  • Commands

Concepts

  • Overview
  • A Columnar Graph Database
  • Versioning System
  • The DataPart System
  • Zero-Locking Architecture
  • Snapshots Isolation

Benchmarks

  • Results Summary
  • Technical Report

Query Language

  • Overview
  • Matching
  • Paths
  • Results and Aggregation
  • NEXT and WHEN
  • Subqueries
  • Functions and Types
  • Writing Data
  • Procedures and Commands
  • CheatSheet

Importing data

  • JSONL
  • CSV
  • Neo4j
  • GML
  • Parquet

Graph Development

  • Create Graph
  • Load Graph
  • Load External data
  • Create a Change
  • List Changes
  • Create Nodes and Edges
  • Update Properties
  • Submit a Change
  • Time Travel
  • Graph Examples

Vector Search

  • Vector Search

Graph Algorithms

  • Shortest Path

Tutorials

  • Example Notebooks

Python SDK

  • Get Started
  • Reference

JavaScript SDK

  • Get Started
  • Reference

Release Notes

  • All Releases
  • TuringDB 3.1

Troubleshooting

  • Troubleshooting

  • The change workflow
  • When you need COMMIT inside a change
  • Failed queries and conflicts
  • CREATE
  • MERGE
  • SET and REMOVE
  • Setting properties from a map
  • DELETE and DETACH DELETE
  • FOREACH
  • Conditional writes
  • Bulk writes
  • Edges between existing nodes
  • Small volumes
Query Language

Writing Data

CREATE, MERGE, SET, REMOVE, DELETE and FOREACH in TuringDB, bulk edges by node ID, and the change workflow that every write goes through.

All writes (CREATE, MERGE, SET, REMOVE, DELETE, FOREACH) must run inside a change. A change is TuringDB’s equivalent of a git branch: you write in an isolated copy and then submit it to the main graph. A write sent outside a change returns a clear message such as Cannot perform CREATE outside of a write transaction.

​
The change workflow

# CHANGE NEW: the client is now on this change
client.new_change()

client.query(
    "CREATE (:Person {name: 'Alice'})"
    "-[:KNOWS]->(:Person {name: 'Bob'})"
)
# ... more writes ...

client.query("CHANGE SUBMIT")       # merge the change into main
client.checkout()                   # return the client to main
  • new_change() returns the change ID and puts the client on that change.
  • After CHANGE SUBMIT the client still points at the submitted change. Call client.checkout() to return to main before running the next query.
  • To abandon a change, run CHANGE DELETE and then client.checkout().
  • new_change() raises if the client is already on a change or on a past commit. Call checkout() first.

See Create a change, Submit a change and Time travelling for more on the versioning model.

​
When you need COMMIT inside a change

COMMIT seals the pending writes of a change. It adds a commit to the history but does not publish anything to main. Whether a later query can see an earlier write depends on what the earlier write did:

An earlier query in the same change did…Visible to later queries before COMMIT?
CREATE or MERGE nodes or edgesTo MERGE, yes. To MATCH, after COMMIT. Run COMMIT so that a later MATCH or MATCH ... CREATE sees the new entities
SET, REMOVE or DELETE on entities that already existedYes, immediately
anything, followed by COMMITYes
writes earlier in the same query, including earlier NEXT stepsYes

Rule of thumb: run COMMIT after any query that creates entities that a later query must MATCH. You can use several COMMITs in one change. CHANGE SUBMIT commits whatever is still pending, so no COMMIT is needed right before it.

client.new_change()
client.query(
    "CREATE (:Person {name: 'Alice'}), (:Person {name: 'Bob'})"
)
# make the new nodes visible to the next query
client.query("COMMIT")
client.query(
    "MATCH (a:Person {name: 'Alice'}), (b:Person {name: 'Bob'})"
    " CREATE (a)-[:KNOWS]->(b)"
)
client.query("CHANGE SUBMIT")
client.checkout()

​
Failed queries and conflicts

  • Recovering from a failed query. If a query stops with an execution error in the middle of a change, the writes it already made stay in the change. The safest recovery is CHANGE DELETE, then redoing the work.
  • Changes are isolated. Main does not see a change’s writes, even committed ones, until the change is submitted. Each change is rebased onto main at submit time.
  • Disjoint edits submit cleanly. When two changes edit the same entity, the second CHANGE SUBMIT reports a conflict, for example This change attempted to update Node 0 (...) which has been modified on main. Conflict detection is coarse: creating an edge to a node that was modified on main also conflicts.
  • A failed submit rejects the whole change but leaves it open. You can fix it and submit again, or run CHANGE DELETE.
  • IDs of newly created nodes and edges are provisional until COMMIT or CHANGE SUBMIT. Read them after committing. IDs of existing nodes are stable across submits and restarts (see node ID lookup).

​
CREATE

CREATE (:Person {name: 'Alice', age: 30})

CREATE (a:Person:Employee {name: 'Bob'})
RETURN a.name, id(a)

CREATE (:Person {name: 'Mick'})
  -[:FRIEND_OF {since: 2020}]->(:Person {name: 'John'})

CREATE (a:T {x: 1}), (b:T {x: 2}), (a)-[:R]->(b)

CREATE p = (:City {name: 'Paris'})
  -[:ROAD {km: 450}]->(:City {name: 'Lyon'})
RETURN p

CREATE (c:City {
  name: 'Li' + 'lle', pop: 2 * 1000, tags: ['a', 'b'],
  info: {zone: 1}, emb: (0.1, 0.2, 0.3)
})

CREATE (n:Item {sku: 'A1'})
SET n.price = 9.99
RETURN n.sku

CREATE (a:W {k: 'a'})
WITH a
CREATE (b:W {k: 'b'})-[:NEXT]->(a)

To connect nodes that already exist, match them first. They must be committed, or created earlier in the same query:

MATCH (a:Person {name: 'Alice'}), (b:Person {name: 'Bob'})
CREATE (a)-[:KNOWS {since: 2021}]->(b)
RETURN a.name, b.name

If you know their native node IDs, address them directly. That is the fastest option:

MATCH (a)
WHERE a = 0
MATCH (b)
WHERE b = 1
CREATE (a)-[:KNOWS {since: 2021}]->(b)

To create many edges at once, put the ID pairs in one UNWIND (see Edges between existing nodes).

Rules:

  • Labels and edge types. Create nodes with a label, CREATE (n:Label), and give each edge a single type, [:TYPE]. Several labels are joined with : or &, and a label or edge type can come from a query parameter: CREATE (n:$label).
  • Labels are set at creation and cannot be changed afterwards.
  • Property types are global. Each property name has one value type across the whole graph (see CALL db.propertyTypes()). If age is an Integer, CREATE (:X {age: 'old'}) and SET n.age = 2.5 are both reported as type incompatibilities, and values are not widened from Integer to Double automatically.
  • Nulls. A key set to null in CREATE is skipped, so {name: null} simply leaves name unset.
  • Write patterns use single hops. Variable-length edges are for reading, and a matched edge variable is not reused in CREATE.
  • Edges are directed. Write the arrow, CREATE (a)-[:R]->(b). Parallel edges and self-loops are allowed.

​
MERGE

MERGE matches the whole pattern or creates it. It supports ON CREATE SET and ON MATCH SET:

MERGE (n:Person {name: 'Alice'})
  ON CREATE SET n.created = true
  ON MATCH SET n.seen = true
RETURN n.name
MATCH (a:Person {name: 'Alice'}), (b:Person {name: 'Carol'})
MERGE (a)-[e:KNOWS]->(b)
  ON CREATE SET e.since = 2024

MERGE (a:Tag {name: 'x'})-[:LINKS]->(b:Tag {name: 'y'})

MATCH (p:Person {name: 'Bob'})
MERGE (p)-[:OWNS]->(c:Car {model: 'Z'})

UNWIND ['a', 'b', 'a'] AS k
MERGE (t:Key {k: k})
RETURN t.k

MERGE deduplicates within one query, so the last example creates two Key nodes, not three.

  • MERGE also finds the nodes and edges that earlier queries of the same change wrote, before any COMMIT, so running the same MERGE twice creates one node.
  • A MERGE key must have a value. A key that is null when the query runs is reported (MERGE cannot match on property 'k', which is null), so filter nulls out first with WHERE k IS NOT NULL.
  • MERGE is the way to avoid duplicates.

​
SET and REMOVE

MATCH (n:Person {name: 'Alice'})
SET n.age = 31

MATCH (n:Person {name: 'Alice'})
SET n.score = n.age * 1.1, n.updated = true

MATCH (p:Product)
SET p.discountPrice = p.price * (1 - 0.15)

MATCH (a:Person)
SET a.band = CASE WHEN a.age > 30 THEN 'senior' ELSE 'junior' END

MATCH (a:Person)
SET a.place = coalesce(a.city, 'unknown')

MATCH (n:Person {name: 'Alice'}), (m:Person {name: 'Bob'})
SET n.age = m.age

MATCH (n:Person {name: 'Alice'})-[e:KNOWS]->(m)
SET e.weight = 0.5

MATCH (n:Person)
WHERE n.age < 18
SET n.isMinor = true

MATCH (n:Person {name: 'Alice'})
SET n.tags = ['a', 'b'], n.meta = {level: 3}

MATCH (n:Person {name: 'Alice'})
SET n.emb = (1.2, 2.0, 0.0, 12.0)

MATCH (n:Person {name: 'Alice'})
SET n.joined = datetime('2024-03-15T10:30:00Z')

MATCH (a:Person)
WITH count(a) AS c
MATCH (s:Stats {name: 'people'})
SET s.total = c

MATCH (n)
WHERE n = 0
SET n.flag = true

UNWIND [0, 1, 2] AS x
MATCH (n)
WHERE n = x
SET n.flag = true

MATCH (n:Person {name: 'Alice'})
SET n.age = null

MATCH (n:Person {name: 'Alice'})
REMOVE n.score, n.flag
  • SET creates the property if it does not exist yet. Setting a property to null clears it, and REMOVE n.prop removes it.
  • The value can be any expression, including a CASE, a function call, a value from another matched entity or a parameter.
  • Address nodes by native node ID for the fastest updates. Batch updates use the same UNWIND form as reads.
  • For a one-off embedding, SET n.emb = (...) is fine. To write embeddings onto many existing nodes, use LOAD EMBEDDING instead of a SET loop.

​
Setting properties from a map

SET n += map adds and updates the properties in the map and keeps the others. SET n = map replaces all of them, so the properties missing from the map are removed:

MATCH (n:Person {name: 'Alice'})
SET n += {city: 'Berlin', score: 1.5}

MATCH (c:Company {name: 'Acme'})
SET c = {name: 'Acme Corp', size: 10}

MATCH (a:Company {name: 'Acme'}), (b:Company {name: 'Globex'})
SET b += a {.founded}

MATCH (:Person {name: 'Alice'})-[r:WORKS_AT]->()
SET r += {since: 2019}
  • A key set to null in the map removes that property: SET n += {city: null}.
  • SET n = {} and SET n = null remove every property of n, and SET n += null changes nothing.
  • The map can come from a parameter, such as SET n += $props, from properties(m), or from a map projection, as in the third query, which copies one property.
  • Each value must fit the property’s type, as with SET n.prop = .... A new property takes the type of its value.

Label changes (SET n:Label) and aggregates directly inside SET (SET n.c = count(*)) are not yet supported. Compute aggregates in a WITH first, as in the Stats example above.

​
DELETE and DETACH DELETE

MATCH (n:Person {name: 'Alice'})
DETACH DELETE n

MATCH (n:Person {name: 'Alice'})-[e:KNOWS]->(m)
DELETE e

MATCH (n:Temp)
WHERE n.v > 3
DELETE n

MATCH (n:Person {name: 'Remy'})-[e]->(m:Person)
DELETE e, n
  • DETACH DELETE removes a node together with all of its edges.
  • Use DETACH DELETE for a node that still has edges. A plain DELETE reports Cannot delete a node with relationships; use DETACH DELETE.
  • To delete a path, delete its nodes or edges.

​
FOREACH

FOREACH runs write clauses once for each element of a list. It does not change the rows of the query:

FOREACH (i IN [1, 2, 3] | CREATE (:Num {v: i}))

FOREACH (nm IN ['x', 'y', 'x'] | MERGE (:Tag {name: nm}))

MATCH (n:Person)
WITH collect(n) AS people
FOREACH (p IN people |
  SET p.reviewed = true, p.nextAge = p.age + 1
)

FOREACH (i IN [1, 2] |
  FOREACH (j IN [10, 20] | CREATE (:Cell {v: i * j}))
)

The second example creates two Tag nodes, since MERGE deduplicates, and the last shows that FOREACH blocks nest.

The clauses inside can use the variables of the row, so FOREACH can hang new nodes off a matched one, or run several clauses per element:

MATCH (a:Person {name: 'Alice'})
FOREACH (i IN range(1, 3) | CREATE (a)-[:OWNS]->(:Item {n: i}))

MATCH (n:Person)
FOREACH (t IN n.tags |
  MERGE (tag:TagNode {name: t})
  CREATE (n)-[:TAGGED]->(tag)
)

The elements of a list property such as n.tags are stored as they are, and a new property takes the type of the values written to it (see map and mixed rows).

Writing only when a condition holds. Loop over a list that is empty when the condition fails:

MATCH (n:Person)
FOREACH (x IN CASE WHEN n.age > 35 THEN [1] ELSE [] END |
  SET n.senior = true
)

A RETURN can follow, since FOREACH keeps the rows: MATCH (n:Person) FOREACH (x IN [1] | SET n.seen = true) RETURN count(*).

​
Conditional writes

The branches of a conditional query can write:

MATCH (n:Person)
CALL (n) {
  WHEN n.age > 30 THEN CREATE (:Senior {name: n.name})
}
RETURN count(*)

​
Bulk writes

Building a new graph? Beyond a few thousand entities, use LOAD PARQUET. It loads 100,000 nodes and 200,000 edges in about 0.2 seconds.

Adding edges between nodes that already exist? Send their native node IDs in pairs, as below: a batch of 10,000 edges takes a few milliseconds.

​
Edges between existing nodes

Read each node’s ID once together with your own key, map your edge list to ID pairs in your application, and create the edges in batches of about 10,000 pairs, passed as a parameter:

ids = client.query(
    "MATCH (n:Person) RETURN n.pid AS pid, id(n) AS id"
)
# .tolist() gives plain ints
key_to_id = dict(zip(ids["pid"].tolist(), ids["id"].tolist()))
pairs = [
    [key_to_id[src], key_to_id[dst]] for src, dst in edge_list
]

client.new_change()
for i in range(0, len(pairs), 10_000):
    client.query(
        "UNWIND $pairs AS p "
        "MATCH (a) WHERE a = p[0] MATCH (b) WHERE b = p[1] "
        "CREATE (a)-[:KNOWS]->(b)",
        {"pairs": pairs[i:i + 10_000]},
    )
client.query("CHANGE SUBMIT")
client.checkout()

In our tests a batch of 10,000 pairs takes about 6 ms as a parameter, against about 25 ms with the same list written into the query text. Edge properties ride along in each row: UNWIND $rows AS p ... CREATE (a)-[:KNOWS {since: p[2]}]->(b) with rows such as [12, 34, 2021]. Use IDs rather than matching both endpoints by a key property (MATCH (a:Person {pid: p[0]})), which reads every Person node for each row.

​
Small volumes

For a few thousand rows, inline the data with UNWIND:

UNWIND range(1, 1000) AS i
CREATE (:Num {v: i})

UNWIND ['Brest', 'Rennes', 'Nantes'] AS nm
MERGE (:City {name: nm})

UNWIND [['Brest', 'FR-29'], ['Rennes', 'FR-35']] AS row
CREATE (:City {name: row[0], code: row[1]})

Rows can also be maps, or lists of mixed types, and their values are stored as they are:

UNWIND [
  {name: 'Brest', pop: 139000},
  {name: 'Rennes', pop: 220000}
] AS row
CREATE (:City {name: row.name, pop: row.pop})

UNWIND [['Brest', 139000], ['Rennes', 220000]] AS row
CREATE (:City {name: row[0], pop: row[1]})
  • A new property takes the type of the values written to it, here a String name and an Integer pop. One write cannot give it two types: One write gives the new property 'v' two types: 'Integer' and 'String'.
  • An existing property keeps its type: Cannot set a property of type 'Int64' to a value of type 'String'. Convert such a value first, for example with toInteger(row.pop).

LOAD CSV can drive writes too. Create the nodes, COMMIT, then create the edges (see CSV import). Alternatively MERGE both endpoints in a single pass, which deduplicates across the rows of one query so no COMMIT is needed:

LOAD CSV 'knows.csv' WITH HEADERS AS row
  MERGE (a:Person {pid: toInteger(row.src)})
  MERGE (b:Person {pid: toInteger(row.dst)})
  CREATE (a)-[:KNOWS {since: toInteger(row.since)}]->(b)

Use UNWIND or FOREACH to loop over a list.

From Python, pass the rows as a parameter. Values in a parameter need no quoting or escaping, and take less room than the same values written into the query text:

rows = [
    {"name": "Brest", "pop": 139000},
    {"name": "O'Brien Town", "pop": 1200},
]
client.query(
    "UNWIND $rows AS row MERGE (c:City {name: row.name}) "
    "SET c.pop = row.pop",
    {"rows": rows},
)

A request, the query text and its parameters together, can be up to 1 MiB. Split larger batches, as in the edge recipe above.

Functions and TypesProcedures and Commands
githublinkedinyoutubediscord