Skip to content

Key Concepts

A @NodeFragment maps one node. Every property of the object is stored, unless it is marked @GraphTransient():

@NodeFragment({ labels: ['Person'] })
export class Person {
@NodeId() uuid: string;
name: string;
bio?: string;
}

A fragment names at least one label. A subclass carries its own labels as well as its superclass’s: see Polymorphism.

Defaults for missing properties. A property the node doesn’t have keeps the class’s initializer. Two decorators handle a stored null:

@NodeFragment({ labels: ['User'] })
export class UserNode {
@NodeId() id: string;
@Default() status = 'active'; // a stored null loads as 'active'
@EmptyWhenAbsent() tags: string[]; // absent or null loads as []; an object loads as {}
}

@EmptyWhenAbsent reads the kind of collection from the type TypeScript records for the field: [] for an array, an empty Set for a set, and {} for an object or a map. A set is stored as a list, and such a field loads it back as a set. TypeScript records a list declared with a union, such as string[] | null under strict null checks, as Object, as it records a map, so name the kind for such a field, or declare it tags?: string[]:

@EmptyWhenAbsent({ kind: 'array' }) tags: string[] | null; // absent loads as [], not {}
@EmptyWhenAbsent({ kind: 'set' }) badges: Set<string> | null; // absent loads as an empty Set

A kind the declared type contradicts, and a field that holds no collection, such as a string, are refused when the model is built.

Storing a set as a list is a change from 3.2, which wrote a set as it was given: Oracle and Postgres held it as {}, and Memgraph as an empty map, without its items. A set field Drivine knows of (see below) loads such a {} as an empty set, and its next save stores it as a list. The refusal of @EmptyWhenAbsent on a field that holds no collection is new too: such a field used to load {}.

Sets. A field that holds a Set loads the list the store holds as a Set, with or without @EmptyWhenAbsent, in a fragment, a view or a relationship fragment. Drivine knows a field holds a set where TypeScript records its type as Set, which it does for a decorated field, whatever the decorator, or where the class initializes the field with a Set. A field neither decorated nor initialized leaves no type at run time, and TypeScript records a union, such as Set<string> | null, as Object: such a field loads the list as an array. Without @EmptyWhenAbsent, a set the node holds nothing for stays absent, or keeps its initializer, and a stored null loads as null.

@GraphProperty('code_set') codes: Set<string>; // decorated: loads as a Set
badges = new Set<string>(); // initialized: loads as a Set
tags: Set<string>; // neither: TypeScript records nothing, so it loads as an array

Loading a set without @EmptyWhenAbsent as a Set is a change from 3.2, which loaded it as the array the store held.

Dates. A field declared a Date loads as a Date on every store, as Neo4j’s and Memgraph’s drivers give one, in a fragment, a view’s root and its relationships, a nested view, a relationship fragment, a path’s end and a @NodeId, through load, loadAll, loadNearest, loadMatching, edges.loadRelated and update (#807). Oracle, Postgres, SQLite and FalkorDB hold a date as its ISO 8601 text, which loaded as that text before. Drivine knows a field is declared a Date as it knows a field holds a set: where TypeScript records its type, for a decorated field, whatever the decorator, or where the class initializes the field with a Date. A field neither decorated nor initialized, or declared with a union such as Date | null, loads as the store gives it: a Date on Neo4j and Memgraph, its text elsewhere. So does a list of dates (Date[]), which TypeScript records as an Array, and a row a QuerySpecification’s .transform maps, which is not the object manager’s. A null loads as null, and a text that is no ISO 8601 date, or a day the month hasn’t, as the text.

@GraphProperty('due_at') due: Date; // decorated: loads as a Date
openedAt = new Date(0); // initialized: loads as a Date
seenAt: Date; // neither: a Date on Neo4j and Memgraph, its text on the other stores

On Oracle, Postgres and SQLite, a save writes each property it leaves as a load gave it exactly as the store held it, byte for byte (#811). So an undecorated Date field, which loads as its text, is saved back as the date, not as a string, and a datetime keeps the nanoseconds and the offset a Date can’t hold, a field declared a Date included. This holds for every save of an object a load made: save, save with from, saveAll, update and patchAll, of a fragment and of a view, its root, its related nodes, its nested views and its relationship fragments, a list of dates among them. A property is unchanged where its value deep-equals what the load gave, a Date by its time; one changed, in place or given anew, is written as any value is, and every property is still written. These cases aren’t recognised, and their undecorated dates are saved as their text:

  • An object copied out of what a load returned, by a spread or structuredClone, is a new object to the save. Save the loaded object, or give it as from. from stands for a view’s root only: a related node of a view’s copy must be the one the load gave, not a copy of it.
  • An entry of a @PropertyBag is written as the load gave it, so a date in a bag is saved as its text.
  • A set is unchanged only in the order the load gave its items: the same items in another order are written afresh.
  • A new Date in an undecorated field is saved as a date but loads as its text, so it can’t round-trip. Declare a field that holds a date with a decorator, or initialize it with a Date.

save, patch, patchAll and edges.relate all write a set as the list of its items, and a @JsonPacked one as the JSON text of that list, which is also what a where compares a packed set field with. In 3.2, patch wrote a packed set as {}, and on Postgres and Oracle so did patch and relate any set, losing its items; a where comparing a packed field with a set compared it with {}, and matched nothing.

Whole numbers past 2^53. A bigint is written as the whole number it is, with every digit, wherever a save, patch, patchAll or edges.relate writes a value: a property, a list’s item, a property bag, a @JsonPacked field, a relationship’s property and a @NodeId. A where compares a field with one as that number too. Before #739, a bigint threw Do not know how to serialize a BigInt on Oracle, Postgres and SQLite. A JavaScript number past 2^53 that is whole is written with its digits too, as a statement binds it: 2^60 as 1152921504606846976, not as its shortest text, 1152921504606847000.

Floats, bytes, typed arrays, NaN and the infinities. On Oracle, Postgres and SQLite, wherever a save, patch, patchAll or edges.relate writes a value, it is held as a CREATE given the same value holds it: the shared compiler’s module writes it for the store (drivine-cypher-spec#329), so a value saved and one a Cypher statement wrote read back alike.

  • Floats. On Oracle every float is held as a binary double, so a cypherFloat(2) saved reads back by Cypher as the float 2.0, not the number 2. On Postgres a whole float is held with its fraction (2.0). A JavaScript number that is whole is an integer, as in a statement’s parameters: give cypherFloat(n) for a whole float. -0 is the float -0.0 (0.0 on Postgres), as no integer is -0. A @NodeId that is a float is found by a load, a delete, edges.relate and loadRelated as the store holds it, as a save finds it: compared as the JSON number 1.0E-7 (not JavaScript’s text 1e-7), and on Oracle as the binary double held.
  • Bytes and typed arrays. Bytes (a Uint8Array, an Int8Array, a Buffer) are held as the list of their signed values, as drivine4j and Neo4j hold them ([1, 2, -1] for 1, 2, 255). A Float32Array or a Float64Array, such as an embedding, is the list of its numbers, each a float; another typed array is the list of its numbers.
  • NaN and the infinities. Oracle holds them, as binary doubles, and SQLite holds an infinity (as 9e999). Where the store’s JSON holds no such number, Postgres’s NaN and infinities and SQLite’s NaN, the value, at any depth, is refused with a DrivineError with the message a CREATE given it is refused with, such as “A statement that writes is given NaN or an infinity, which Postgres’s jsonb holds as no number: it would store another value in its place.” The refusal comes before anything is written, patchAll’s first statement included.

A load gives a field’s whole numbers the type the model declares, not one their size picks. A field declared a bigint loads each as a bigint, with the digits Postgres and SQLite kept. Three things declare it:

  • a decorated field TypeScript records as bigint, such as @NodeId() id: bigint;
  • a field the class initializes with a bigint, such as count: bigint = 0n;
  • @BigIntProperty(), for a field TypeScript records otherwise: a union such as bigint | null, a list, a map, a property bag or a @JsonPacked field.

Any other field loads a whole number as a JavaScript number, past 2^53 the nearest, as before. So declare a field that holds whole numbers past 2^53 to load it back exactly. A view’s @Count or @Aggregate field loads by the same rule, and a groups key or aggregate, which has no field to declare, as a number. On Oracle a declared field still loads a bigint, but past 2^53 the driver has already rounded it (#737). Compiled Cypher has no model to go by: there a whole number past 2^53 always comes back as a bigint (#735).

2. RelationshipFragment: a Relationship’s Properties

Section titled “2. RelationshipFragment: a Relationship’s Properties”

A @RelationshipFragment holds the properties of a relationship, and the node it leads to:

@RelationshipFragment()
export class WorkHistory {
startDate: string; // a property of the relationship
role: string; // and another
@TargetNode() target: Organization; // the node it leads to
}

Use it for employment history, transactions, audit trails, or any relationship with data of its own.

A @GraphView composes fragments and relationships into one result. @Root marks where the query starts:

@GraphView()
export class PersonCareer {
@Root() person: Person;
@GraphRelationship({ type: 'WORKS_FOR', target: () => WorkHistory })
employmentHistory: WorkHistory[] = [];
}

@GraphRelationship takes:

Option Meaning
type The relationship type.
direction Direction.OUTGOING (the default), INCOMING or UNDIRECTED.
target The class of the related item: a fragment, a relationship fragment or a view, as a function so that classes may refer to each other in either order. It is required for a list, since TypeScript records only Array as a list’s type. For a single item it defaults to the property’s type.
required Only roots that have the relationship are loaded. TypeScript erases ?:, so a view says this rather than the type: see Required Relationships.
maxDepth For a recursive relationship, how deep to expand. Defaults to 1.

When a view refers to a class declared later in the same module, type the property with Related<T>, so the decorator metadata doesn’t read the class before it exists: @GraphRelationship({ type: 'TO_B', target: () => B }) b?: Related<B>.

4. Recursive Relationships: Hierarchies and Ontologies

Section titled “4. Recursive Relationships: Hierarchies and Ontologies”

A view whose relationship targets its own class is expanded to maxDepth levels:

@NodeFragment({ labels: ['Location'] })
export class Location {
@NodeId() uuid: string;
name: string;
type: string;
}
@GraphView()
export class LocationHierarchy {
@Root() location: Location;
@GraphRelationship({ type: 'HAS_LOCATION', target: () => LocationHierarchy, maxDepth: 3 })
subLocations: LocationHierarchy[];
}

At the last level a list is [] and a single item is undefined. To walk upwards, make another view with direction: Direction.INCOMING. A query can override the depth:

await gom.loadAll(LocationHierarchy, (q) => ({
where: q.location.type.eq('continent'),
depth: { subLocations: 5 }
}));

Cycles through other views (A → B → A) are expanded to maxDepth as well. A view nested in itself is saved, each level one relationship from the one above. A list of fragments read over several hops (maxDepth above 1 on a list of a fragment) is loaded and never written.

5. Path Traversal: Skipping Intermediate Nodes

Section titled “5. Path Traversal: Skipping Intermediate Nodes”

@GraphRelationship is one hop. @GraphPath follows several and maps only the node at the end:

@GraphView()
export class ActorDirectors {
@Root() actor: Actor;
@GraphPath([hop('ACTED_IN', Direction.OUTGOING, 'Movie'), hop('DIRECTED_BY')], { target: () => Director })
directors: Director[];
}

Each node at the end is returned once: an actor who made two movies with one director gets that director once. A hop’s label constrains the node it reaches. required: true keeps only the roots the path leads somewhere from. A path is read-only.

One hop may name an order: a property of the node it reaches, lowest first unless ascending is false. A list then holds its targets in the order of the first node of that hop that leads to each, and a single field holds the target the first such node leads to:

@GraphView()
export class SessionStarter {
@Root() session: Session;
// who wrote the earliest message
@GraphPath([hop('HAS_MESSAGE', Direction.OUTGOING, 'Message', 'sentAt'), hop('AUTHORED_BY')], { target: () => Person })
startedBy?: Person;
}

A node of the ordered hop without the property comes last, whichever way the path is read. Targets whose first nodes hold equal values come in no set order. A text of digits such as '0100' is ordered as text, and an empty text as a text, the lowest one. On Neo4j and the SQL backends a date is ordered by its moment, an offset’s included, not by its text. Where the property holds values of several kinds, Neo4j, Memgraph and the SQL backends order them by kind as Cypher’s ORDER BY does: lowest first a map, a list, a temporal value, a text, a boolean, then a number, and the other way highest first. On Neo4j and Memgraph the path is sorted by the engine’s own ORDER BY. FalkorDB orders them as its own ORDER BY does. A group key’s path names no order: pathKey refuses one.

6. Aggregates: Counting and Summarising Without Loading

Section titled “6. Aggregates: Counting and Summarising Without Loading”

@Count and @Aggregate compute a number for each root in the query, so you don’t load a list just to size it:

@GraphView()
export class ActorStats {
@Root() actor: Actor;
@Count('ACTED_IN') movieCount: number;
@Aggregate({ function: AggregateFunction.AVG, type: 'RATED', property: 'score' }) avgRating?: number;
@Aggregate({ function: AggregateFunction.SUM, type: 'RATED', property: 'score' }) totalRating: number;
}

SUM and COUNT over nothing are 0; AVG, MIN and MAX over nothing are undefined. Aggregates follow one hop and belong to one root. To group nodes by a key and rank the groups, use a grouped read.