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

  • Built-in functions
  • String functions
  • Lists
  • Conversions
  • Arithmetic in RETURN and SET
  • Dates and durations
  • Maps
  • Map projection
  • Points
  • How results come back
  • Embeddings
Query Language

Functions and Data Types

Built-in functions, how values come back to the SDKs, dates and durations, maps and map projection, points, and embedding comparison in TuringDB v3.

​
Built-in functions

Function names are case-insensitive, like keywords: toInteger, TOINTEGER and ToInteger are the same function. Functions in a namespace are written with a dot, such as coll.indexOf and point.distance.

CategoryFunctionsNotes
Entityid(x), elementId(x), labels(n), type(r), startNode(r), endNode(r), keys(x), properties(x)labels and keys return lists. properties returns a map of a node’s, an edge’s or a map’s properties. type returns a string. elementId returns the same integer as id. startNode(r).name works
Pathnodes(p), relationships(p), length(p)Lists of IDs. Read properties through a comprehension
Listsize, length, head, last, tail, reverse, isEmpty, range(start, end[, step]), reduce, coll.indexOf(list, value)size, length and reverse also work on strings, and isEmpty on strings and maps. range bounds are inclusive. See Lists
Predicatesall, any, none, single (x IN list WHERE ...), allReduce, exists(pattern)See Lists and pattern predicates
ConversiontoInteger, toFloat, toString, toBoolean, toIntegerOrNull, toFloatOrNull, toStringOrNull, toBooleanOrNull, coalesce(a, b, ...)toInteger accepts strings, numbers and booleans, and toFloat strings and numbers. Both return null for a bad string. toBoolean accepts strings and integers. toString formats DateTime, Duration and Point values. The OrNull forms return null for any value they cannot convert. coalesce arguments may mix types
StringtoUpper, toLower, trim, ltrim, rtrim, substring(s, start[, length]), left(s, n), right(s, n), split(s, delimiter), replace(s, search, replacement), reverse, char_length (or character_length), normalize(s[, NFC|NFD|NFKC|NFKD])Positions start at 0. split also takes a list of delimiters. Plus the operators STARTS WITH, ENDS WITH, CONTAINS, IS NORMALIZED and ||
Mathabs, sign, ceil, floor, round, sqrt, exp, log, log10, pi(), e()Trigonometry: sin, cos, tan, cot, asin, acos, atan, degrees, radians, haversin
Temporaldatetime(isoString), datetime(epochSeconds), datetime({year: 2024, month: 3, day: 15}), datetime(), duration({days: 2, hours: 3}), duration(micros)See Dates and durations
Spatialpoint({x, y}), point({latitude, longitude}), point.distance(a, b), point.withinBBox(p, lowerLeft, upperRight)See Points
Embeddingcosine_similarity(a, b), euclidean_distance(a, b)Arguments must be Embeddings, not lists. See Vector search
Aggregatecount, collect, sum, avg, min, max, stDev, stDevP, percentileCont, percentileDiscSee Aggregation
MATCH (n)-[e]->(m)
RETURN labels(n), type(e), labels(m)

MATCH (n:Person)
RETURN toUpper(n.name), toString(n.age)

MATCH (n:Person)
WHERE n.age > toInteger('29')
RETURN n.name

MATCH (n:Person)
RETURN n.name, n.age * toFloat('1.07')

RETURN toBoolean('true')

RETURN abs(-3), round(2.5), sqrt(16.0), pi()

MATCH (n:Person)
RETURN n.name, coalesce(n.nickname, n.name)

RETURN substring('hello', 1, 3), left('hello', 2),
  split('a,b,c', ','), replace('aXbX', 'X', '-')

MATCH (n:Person)
WHERE toLower(n.name) STARTS WITH 'a'
RETURN n.name

MATCH (n:Person {name: 'Alice'})
RETURN keys(n), properties(n), elementId(n)

RETURN toIntegerOrNull('x'),
  toString(datetime('2024-03-15T10:30:00Z'))

​
String functions

Positions are 0-based, and substring without a length runs to the end of the string:

RETURN substring('hello', 1, 3) AS s,
  substring('hello', 2) AS rest

RETURN left('hello', 2) AS l, right('hello', 3) AS r

RETURN split('a.b.c', '.') AS parts,
  replace('banana', 'a', 'o') AS swapped

RETURN split('a,b;c', [',', ';']) AS parts

RETURN char_length('héllo') AS chars, size('héllo') AS alsoChars

MATCH (n:Person)
RETURN toUpper(left(n.name, 1)) + toLower(substring(n.name, 1))
  AS display

split with a list of delimiters splits on each of them, so the fourth query returns ['a', 'b', 'c'].

normalize converts a string to a Unicode normal form (NFC by default, or NFD, NFKC, NFKD), and IS NORMALIZED tests for one:

RETURN normalize('fi', NFKC) AS plain,
  'café' IS NFC NORMALIZED AS composed

​
Lists

RETURN isEmpty([]) AS emptyList, isEmpty('') AS emptyString,
  isEmpty({}) AS emptyMap

MATCH (n:Person {name: 'Carol'})
RETURN coll.indexOf(n.tags, 'vip') AS position,
  coll.indexOf(n.tags, 'admin') AS missing

RETURN
  allReduce(t = 0, x IN [1, 2, 3] | t + x, t < 10) AS under10,
  allReduce(t = 0, x IN [1, 2, 3] | t + x, t < 5) AS under5
  • coll.indexOf(list, value) returns the position of the first element equal to value, or -1. The second query returns 1 and -1.
  • allReduce(acc = init, x IN list | step, predicate) folds the list like reduce, and is true when the predicate holds for the accumulator after every step. The initial value is not tested, and an empty list gives true. It stops at the first step that fails, so later steps are not computed. Over a path, it tests a running total at each hop. The third query returns true and false.
  • isEmpty, coll.indexOf and allReduce return null for a null list.

​
Conversions

The strict conversions return null for a string they cannot read, and reject other values they cannot convert. The OrNull forms return null instead of rejecting:

RETURN toInteger('12') AS i, toInteger('x') AS bad,
  toInteger(true) AS fromBool, toBoolean(1) AS b

RETURN toIntegerOrNull('12') AS a, toFloatOrNull('2.5') AS c,
  toBooleanOrNull('yes') AS d, toStringOrNull(3.5) AS e

RETURN toString(duration({days: 2, hours: 3})) AS iso

toString writes a Duration in ISO 8601 form, so the last query returns PT51H.

In v3, type(e) returns an edge’s type as a string. It replaces edgeType() from earlier versions.

The function library keeps growing. rand(), date(), timestamp(), atan2(), isNaN() and the two-argument round(x, digits) are not yet available, so compute those in your application.

​
Arithmetic in RETURN and SET

Arithmetic expressions work anywhere an expression is allowed:

MATCH (n:Person)
RETURN n.age * 12

MATCH (n:Person)
RETURN n.name, n.age + 5 AS adjusted, n.age / 2

MATCH ()-[r]->()
WHERE r.since > 0
RETURN r.since / 10 * 100

+ - * / % ^ are supported. Integer / truncates, and ^ returns a Double. + and || concatenate strings and lists, 'x' + 1 gives 'x1', and [1, 2] + 3 gives [1, 2, 3]. A list plus null is null.

​
Dates and durations

DateTime and Duration are first-class types:

RETURN datetime('2024-03-15T10:30:00Z') AS d

RETURN datetime('2024-03-15') AS midnight

RETURN datetime(1700000000) AS fromEpoch

RETURN datetime({
  year: 2024, month: 3, day: 15, hour: 10, minute: 30
}) AS fromParts

RETURN datetime('2024-03-15T10:30:00Z')
  + duration({days: 1, hours: 2}) AS later

RETURN datetime('2024-03-16T00:00:00Z')
  - datetime('2024-03-15T00:00:00Z') AS elapsed

RETURN datetime('2024-03-15T10:30:00Z').year,
  datetime('2024-03-15T10:30:00Z').month

RETURN duration({days: 2, hours: 3}).hours

Durations can be added, subtracted, scaled, compared, summed and averaged:

RETURN duration({hours: 36}) + duration({hours: 12}) AS total

RETURN duration({days: 2, hours: 12}) - duration({days: 1})
  AS remaining

RETURN duration({days: 2}) * 3 AS threeTimes

RETURN duration({hours: 36}) / 2 AS half

RETURN duration({hours: 1}) > duration({minutes: 30}) AS longer

UNWIND [duration({hours: 1}), duration({hours: 2})] AS d
RETURN sum(d) AS total, avg(d) AS mean
  • datetime values are stored as microseconds since the Unix epoch, normalised to UTC. A date-only string means midnight, and an offset (+02:00) is converted to the equivalent UTC instant.
  • datetime({...}) builds a datetime from its parts: year, then optionally month, day, hour, minute, second, millisecond, microsecond and nanosecond. Missing parts default to the start of the period, so datetime({year: 2024}) is midnight on 1 January. A part needs the ones above it, as in The datetime component month needs the component year. A timezone key takes an offset, such as '+02:00' or 'Z', and {epochSeconds: 1700000000} also works.
  • duration is a signed count of microseconds. It has no month component, because a month has no fixed length. duration(<integer>) reads the number as microseconds.
  • Components are available as properties: d.year, d.month, d.day, d.hour, and so on. On a duration, dur.days, dur.hours, … give the total in that unit, so duration({days: 2, hours: 3}).hours is 51.
  • <, >, min and max work on temporal values, and sum and avg on durations.
  • From Python, pass a time-zone-aware datetime.datetime as a parameter for a DateTime, and a datetime.timedelta for a Duration: client.query("RETURN $since + duration({days: 1}) AS next", {"since": datetime(2024, 1, 1, tzinfo=timezone.utc)}).
  • When you import JSONL you can declare which properties are DateTime or Duration with WITH DATETIMES [...] and WITH DURATIONS [...].

​
Maps

Maps can be built, returned, compared, sorted and stored as node or edge properties, and their keys can be read anywhere in a query:

RETURN {name: 'Alice', tags: ['a', 'b']} AS m

WITH {a: 1, b: 'x'} AS m
RETURN m.a, m['b']

WITH {a: {b: 2}} AS m
RETURN m.a.b

WITH {a: 1, b: 2} AS m
UNWIND keys(m) AS k
RETURN k, m[k]

UNWIND [{a: 1}, {a: 2}] AS m
RETURN m.a

WITH [{a: 1}, {a: 2}] AS ms
RETURN ms[1].a, [m IN ms | m.a]

MATCH (n:Person {name: 'Alice'})
RETURN properties(n).name, keys(n), n['age']

MATCH (n:Person)
RETURN collect({name: n.name, city: n.city}) AS people
  • m.key and m['key'] read a key written in the query, and m[k] a key held in a variable. A chain such as m.a.b reads through nested maps, and a map stored as a property reads the same way: n.meta.level, keys(n.meta).
  • A map value can be a node, a datetime or any other value, and reads through it: WITH {p: n} AS m RETURN m.p.name, or m.d.year for a datetime under d.
  • Keys can be any word, keywords included: WITH {count: 3, order: 'x'} AS m RETURN m.count, m.order. A key written twice keeps its last value: {a: 1, a: 2} is {a: 2}.
  • collect() gathers maps, and collect(DISTINCT ...) compares them entry by entry.
  • A value read from a map can be stored as a property directly, as in CREATE (:City {name: row.name}). The property takes the type of the value (see Bulk writes).

​
Map projection

A map projection builds a map out of a node, an edge or a map, picking the entries you need:

MATCH (n:Person {name: 'Alice'})
RETURN n {.name, .age} AS person

MATCH (n:Person {name: 'Dave'})
RETURN n {.*} AS everything

MATCH (n:Person {name: 'Alice'})
RETURN n {.name, nextAge: n.age + 1} AS m

MATCH (n:Person)-[:WORKS_AT]->(c:Company)
RETURN c.name, collect(n {.name, .city}) AS staff

MATCH (n:Person {name: 'Alice'})
WITH n, 'x' AS extra
RETURN n {.name, extra} AS m

WITH datetime('2024-03-15T10:30:00Z') AS d
RETURN d {.year, .month} AS parts
  • .key holds the property key, or null when it is missing. .* holds every property, key: expression a computed value, and a bare variable x its value under the key x.
  • On a datetime, a duration or a point, .key reads a component: the last query returns {month: 3, year: 2024}.
  • An entry written explicitly wins over the one .* reads under the same key, wherever .* stands: n {.*, age: n.age + 1}.
  • A null node, such as an unmatched OPTIONAL MATCH, projects to null.

​
Points

A point is a location, 2D or 3D, either on a plane (cartesian) or on the Earth (WGS-84). point() builds one from a map:

RETURN point({x: 1, y: 2}) AS flat,
  point({x: 1, y: 2, z: 3}) AS space

RETURN point({latitude: 51.5074, longitude: -0.1278}) AS london

WITH point({latitude: 51.5074, longitude: -0.1278}) AS p
RETURN p.latitude, p.longitude, p.srid, p.crs

RETURN point.distance(
  point({x: 0, y: 0}), point({x: 3, y: 4})
) AS d

RETURN round(point.distance(
  point({latitude: 51.5074, longitude: -0.1278}),
  point({latitude: 48.8566, longitude: 2.3522})
)) AS londonToParis

RETURN point.withinBBox(
  point({x: 1, y: 1}), point({x: 0, y: 0}), point({x: 2, y: 2})
) AS inside

The keys of the map choose the coordinate reference system (CRS):

KeysCRSSRID
x, ycartesian7203
x, y, zcartesian-3d9157
longitude, latitudewgs-844326
longitude, latitude, heightwgs-84-3d4979
  • A crs: 'wgs-84' or srid: 4326 key chooses the CRS explicitly, and x and y then hold the longitude and the latitude.
  • Components. p.x, p.y and p.z read the coordinates, and p.longitude, p.latitude and p.height the same ones on a WGS-84 point. p.crs is the CRS name and p.srid its SRID. Reading p.z on a 2D point is an error.
  • Checks. Coordinates must be numbers (point() reads a number for 'x', not 'String'), and a latitude must lie in [-90, 90]. A longitude outside [-180, 180] wraps around. A null map or a null coordinate gives null.
  • point.distance(a, b) is the straight-line distance between two cartesian points. Between two WGS-84 points it is the great-circle distance in metres, on a sphere of the mean Earth radius (6,371,008.8 m), so the fifth query returns about 343,557 m. It is null for two points of different CRSs.
  • point.withinBBox(p, lowerLeft, upperRight) tests whether p lies in the box, bounds included. On WGS-84, a lowerLeft east of upperRight makes a box that crosses the 180th meridian.
  • Comparing and aggregating. Points work with =, <, ORDER BY, DISTINCT, grouping, count, collect, min and max, ordered by SRID, then x, y and z. avg of points of one CRS is their centroid.
  • toString(p) writes point({x: 2.3522, y: 48.8566, crs: 'wgs-84'}).

Store a point as a property like any other value, and filter on distance:

CREATE
  (:City {name: 'Paris',
    at: point({latitude: 48.8566, longitude: 2.3522})}),
  (:City {name: 'London',
    at: point({latitude: 51.5074, longitude: -0.1278})})

MATCH (c:City)
WHERE point.distance(
  c.at, point({latitude: 51.5074, longitude: -0.1278})
) < 400000
RETURN c.name

Points can also be imported: from JSONL with WITH POINTS [...], and from the geometry columns of GeoParquet files.

​
How results come back

client.query() returns a pandas DataFrame. The column types follow the query’s value types:

Typepandas dtype
Stringstring
IntegerInt64
Unsigned integer (IDs, count, length(p))UInt64
Doublefloat64
Booleanboolean
Listobject (Python list)
Mapobject (dict)
Embeddingobject (numpy float32 array)
DateTimedatetime64[us, UTC]
Durationtimedelta64[us]
Pointobject (turingdb.Point, with srid, x, y, z and crs)
Node or edge (RETURN n)UInt64 (internal ID, null when an OPTIONAL MATCH found nothing)
Named path (RETURN p)object (list of IDs, node and edge alternating: [0, 0, 1])

A DateTime or a Duration inside a list or a map comes back as a time-zone-aware datetime.datetime or a datetime.timedelta. Doubles keep their full precision (0.1 + 0.2 comes back as 0.30000000000000004). NaN and infinities come back as the floats nan and inf, and NaN sorts after every number. The JavaScript SDK has its own mapping, see Value types.

​
Embeddings

Embeddings are stored as ordinary properties (type Embedding) and compared with cosine_similarity (true cosine) and euclidean_distance. Both work in RETURN, WHERE and ORDER BY:

MATCH (n:Document)
RETURN n.title,
  cosine_similarity(n.emb, (0.4, 0.3, 0.8, 0.1)) AS sim
ORDER BY sim DESC LIMIT 10

MATCH (n:Document)
RETURN n.title, euclidean_distance(n.emb, (0.4, 0.3, 0.8, 0.1))

This is a brute-force scan over the matched nodes. For large collections, build a vector index.

SubqueriesWriting Data
githublinkedinyoutubediscord