UPSERT is the first thing to get right in this module because getting it wrong is a correctness bug rather than a slow query. The syntax is natural - UPSERT {lookup} INSERT {...} UPDATE {...} IN collection - and it does exactly what it looks like: find a document matching the lookup, insert if absent, update if present.
And under concurrency, without a unique index on the attributes in the lookup, two simultaneous upserts can both find nothing and both insert. You get duplicates, in a collection where your whole model assumed one. Nothing errors. The fix is simple and mandatory: a unique persistent index on exactly the attributes the lookup uses, which turns the race into a conflict error you retry. Better still, where you can, choose a deterministic _key and use an insert with an overwrite mode instead - a single-document operation is atomic by definition, so the race cannot occur. Prefer that whenever the natural key is derivable, and reserve UPSERT for genuinely compound lookups where it is backed by a unique index.
JSON Schema validation is a schema property on the collection: a JSON Schema, a level controlling how strictly it applies, and a message. The levels matter: strict validates every insert and update, moderate validates new documents and updates to already-valid ones, new validates only inserts, and none disables it. The thing to understand: validation applies on write, and adding a schema does not retroactively validate what is already there. So a collection with a schema can be full of documents that violate it, and finding out requires a scan you write yourself. Add the schema early, or audit when you add it late - and either way write the audit query, because "the schema is there" is not the same as "the data conforms".
The query patterns worth internalising come down to one principle: know what each pattern costs. A DOCUMENT() lookup by identifier is a primary index hit and is the cheapest thing you can do - prefer it to a join whenever you hold the identifier. A nested FOR with a relating FILTER is a join, and it needs an index on the filtered attribute or it is a nested scan. A subquery in a LET is evaluated per outer row unless it is independent, which is the classic accidental N+1 in AQL. COLLECT sorts, and COLLECT ... OPTIONS {method: "hash"} can avoid it when you do not need ordered groups. LIMIT placement matters enormously - before a subquery rather than after it changes the work by orders of magnitude.
Graph modelling asks the same question as the previous course and ArangoDB's answer is cleaner because edges are first-class documents. Use an embedded reference when the relationship is a plain attribute you will not traverse; use an edge when you will traverse it, when it carries properties, or when there can be several of the same kind between two documents. Because an edge is a document, the second case costs nothing extra - there is no reason to avoid putting properties on an edge here, which is not true of every graph database.
One edge collection per relationship type, or one with a type attribute? The honest answer: separate collections are usually better, because a traversal naming a specific edge collection reads only that collection's edges, while a single collection with a type filter reads every edge and then discards most of them. The exception is when you genuinely traverse across types in one query and the types are numerous; then one collection with a good index may be simpler. Measure it on your density - the difference is often large.
Named graphs against anonymous traversals. A named graph is a stored definition listing edge collections with their permitted vertex collections, and it gives you two things: traversals written as GRAPH 'name' rather than naming collections, and enforcement - an edge whose endpoints are not in the declared vertex collections is rejected. An anonymous traversal names edge collections directly and skips both. The guidance: use a named graph when the shape is a real invariant you want enforced, which for a knowledge graph it usually is, and anonymous traversals for ad-hoc analysis and for cases where you deliberately want an edge type to span collections the graph definition would forbid.
Traversal syntax, with the one feature that matters most for performance: PRUNE. A traversal is FOR v, e, p IN min..max OUTBOUND|INBOUND|ANY start edgeCollection, giving you the vertex, the edge and the whole path. FILTER on the result discards paths after they have been walked. PRUNE stops the descent at a condition, so the paths below are never walked at all. On a dense graph that is the difference between a fast query and an incident, and it is covered properly in Module 4 - but start using it now, because retrofitting it means re-reasoning about every traversal you wrote.
Laboratory exercise 2 - two models, measured on both deployments.
Design two competing models for the knowledge graph. The contrast that matters: one with a separate edge collection per relationship type, and one with a single edge collection carrying a type attribute. Use named graphs for both so the comparison is clean.
Implement both and load at least 20 million documents and 60 million edges into each, on both deployments.
Implement a common query set against both models and both deployments - so four numbers per query - covering: an entity by key; entities filtered and sorted; a count by type; an entity with its direct relationships; a two-hop neighbourhood filtered by type; a three-hop path between two entities; the documents attached to an entity's neighbourhood; and an aggregation over a traversal result. The four-number table is the module's main artefact and it answers two questions at once.
Demonstrate the UPSERT race, because the demonstration is what makes the rule stick: run 500 concurrent upserts on the same logical entity without a unique index and count the duplicates. Then add the unique index, re-run, and show conflicts instead of duplicates with your retry handling them. Then implement the deterministic-key alternative and show it needs neither.
Demonstrate validation honestly: add a schema to a collection that already contains violating documents, show that nothing is rejected retroactively, then write the audit query that finds them. Test each level and record the difference.
Demonstrate named graph enforcement: attempt to create an edge whose endpoints are outside the declared vertex collections and show the rejection; then do the same with an anonymous traversal's collections and show it accepted. That is the integrity argument, made concrete.
Then show PRUNE against FILTER on one three-hop query - just the pair of numbers, as a preview of Module 4.
Deliverable: both models, the four-number query table, the UPSERT race demonstrated and all three fixes, the retroactive validation demonstration with the audit query, the named graph enforcement demonstration, the PRUNE preview, and a page arguing for one model with the numbers behind it.
// ==================================================================
// *** UPSERT FIRST, BECAUSE GETTING IT WRONG IS A CORRECTNESS BUG
// *** RATHER THAN A SLOW QUERY. ***
// ==================================================================
UPSERT { name: @name, kind: @kind }
INSERT { name: @name, kind: @kind, created: DATE_NOW() }
UPDATE { seen: DATE_NOW() }
IN entity
// *** UNDER CONCURRENCY, WITHOUT A UNIQUE INDEX ON THE LOOKUP
// *** ATTRIBUTES, TWO SIMULTANEOUS UPSERTS CAN BOTH FIND NOTHING AND
// *** BOTH INSERT. You get DUPLICATES in a collection where your
// *** whole model assumed one. NOTHING ERRORS. ***
//
// 500 concurrent upserts, same logical entity, NO unique index:
// -> *** 7 documents where there should be 1 ***
//
// *** FIX 1, MANDATORY: a UNIQUE PERSISTENT INDEX ON EXACTLY THE
// *** ATTRIBUTES THE LOOKUP USES *** - it turns the race into a
// CONFLICT ERROR YOU RETRY:
// db.entity.ensureIndex({ type: "persistent",
// fields: ["name", "kind"], unique: true });
// -> 500 concurrent upserts: 1 document, 6 retried conflicts.
//
// *** FIX 2, BETTER WHERE YOU CAN: A DETERMINISTIC _key AND AN
// *** INSERT WITH AN OVERWRITE MODE. A SINGLE-DOCUMENT OPERATION IS
// *** ATOMIC BY DEFINITION, SO THE RACE CANNOT OCCUR: ***
INSERT { _key: CONCAT(@kind, "--", @slug), name: @name, kind: @kind,
seen: DATE_NOW() }
INTO entity OPTIONS { overwriteMode: "update", keepNull: false }
// *** PREFER THIS WHENEVER THE NATURAL KEY IS DERIVABLE *** , and
// reserve UPSERT for genuinely COMPOUND lookups backed by a unique
// index.
// ==================================================================
// JSON SCHEMA VALIDATION - and *** WHAT IT DOES NOT CHECK. ***
// ==================================================================
// db.entity.properties({ schema: {
// rule: {
// type: "object",
// required: ["name", "kind"],
// properties: {
// name: { type: "string", minLength: 1, maxLength: 400 },
// kind: { type: "string",
// enum: ["person","organisation","place",
// "product","event"] },
// founded: { type: "number", minimum: 1500 }
// },
// additionalProperties: true
// },
// level: "strict",
// message: "entity failed validation"
// }});
//
// LEVELS:
// strict every INSERT and UPDATE
// moderate new documents, and updates to ALREADY-VALID ones
// new INSERTS only
// none off
//
// *** THE THING TO UNDERSTAND: VALIDATION APPLIES ON WRITE, AND
// *** ADDING A SCHEMA DOES NOT RETROACTIVELY VALIDATE WHAT IS
// *** ALREADY THERE. *** A collection WITH a schema can be FULL of
// documents that VIOLATE it. *** SO WRITE THE AUDIT QUERY: ***
FOR e IN entity
FILTER e.name == null OR e.kind == null
OR e.kind NOT IN ["person","organisation","place","product","event"]
LIMIT 100
RETURN { _key: e._key, name: e.name, kind: e.kind }
// *** "THE SCHEMA IS THERE" IS NOT THE SAME AS "THE DATA
// *** CONFORMS." *** Add the schema early, or audit when you add it
// late - and run the audit in CI either way.
// ==================================================================
// QUERY PATTERNS: one principle - *** KNOW WHAT EACH ONE COSTS. ***
// ==================================================================
// CHEAPEST thing you can do - a PRIMARY INDEX hit:
RETURN DOCUMENT("entity/acme-corp")
// *** PREFER IT TO A JOIN WHENEVER YOU HOLD THE IDENTIFIER. ***
// A JOIN - needs an INDEX ON THE FILTERED ATTRIBUTE or it is a
// NESTED SCAN:
FOR d IN document
FOR e IN entity FILTER e.slug == d.subject_slug
RETURN { d, e }
// *** THE CLASSIC ACCIDENTAL N+1 IN AQL: a subquery in a LET is
// *** evaluated PER OUTER ROW unless it is INDEPENDENT: ***
FOR e IN entity // 20,000,000 rows
LET docs = (FOR d IN document FILTER d.about == e._id RETURN d)
RETURN { e, docs } // *** 20,000,000 subqueries ***
// -> *** LIMIT FIRST. Placement changes the work by orders of
// *** magnitude: ***
FOR e IN entity
FILTER e.kind == "organisation"
SORT e.name LIMIT 50 // *** 50 rows, THEN ***
LET docs = (FOR d IN document FILTER d.about == e._id LIMIT 5 RETURN d)
RETURN { e, docs } // 50 subqueries
// COLLECT SORTS. If you do not need ordered groups:
FOR e IN entity
COLLECT kind = e.kind WITH COUNT INTO n OPTIONS { method: "hash" }
RETURN { kind, n }
// ==================================================================
// GRAPH MODELLING. Edges are FIRST-CLASS DOCUMENTS, which makes the
// answer cleaner here.
// ==================================================================
// EMBEDDED REFERENCE a plain attribute you will NOT TRAVERSE
// *** AN EDGE *** you WILL TRAVERSE it, it CARRIES PROPERTIES,
// or there can be SEVERAL of the same kind
// between two documents
//
// *** BECAUSE AN EDGE IS A DOCUMENT, PROPERTIES ON IT COST NOTHING
// *** EXTRA - THERE IS NO REASON TO AVOID PUTTING THEM THERE, WHICH
// *** IS NOT TRUE OF EVERY GRAPH DATABASE: ***
INSERT { _from: "entity/acme-corp", _to: "entity/jane-doe",
type: "employs", role: "CTO",
since: "2023-04-01", confidence: 0.94, source: "filing-8812" }
INTO employs
// *** ONE EDGE COLLECTION PER TYPE, OR ONE WITH A type ATTRIBUTE? ***
// *** SEPARATE COLLECTIONS ARE USUALLY BETTER: a traversal naming a
// *** SPECIFIC edge collection READS ONLY THAT COLLECTION'S EDGES,
// *** while one collection with a type FILTER READS EVERY EDGE AND
// *** DISCARDS MOST OF THEM: ***
// 2-hop, 60,000,000 edges, filtered to "employs":
// separate collections *** 14 ms ***
// one collection + type filter 890 ms
// THE EXCEPTION: you genuinely traverse ACROSS types in one query
// and the types are NUMEROUS - then one collection with a good
// index may be simpler. *** MEASURE IT ON YOUR DENSITY; THE
// DIFFERENCE IS OFTEN LARGE. ***
// ==================================================================
// NAMED GRAPHS AGAINST ANONYMOUS TRAVERSALS.
// ==================================================================
// var graph = require("@arangodb/general-graph");
// graph._create("knowledge", [
// graph._relation("employs", ["entity"], ["entity"]),
// graph._relation("located_in", ["entity"], ["place"]),
// graph._relation("mentions", ["document"], ["entity"])
// ]);
//
// A NAMED GRAPH gives you TWO things:
// 1. traversals written as GRAPH 'knowledge'
// 2. *** ENFORCEMENT - an edge whose endpoints are NOT in the
// *** DECLARED VERTEX COLLECTIONS IS REJECTED. ***
// INSERT { _from: "document/d1", _to: "place/p1" } INTO employs
// -> *** rejected: not in the graph definition ***
// An ANONYMOUS traversal names edge collections directly and SKIPS
// BOTH - the same insert is ACCEPTED.
//
// *** THE GUIDANCE: A NAMED GRAPH WHEN THE SHAPE IS A REAL INVARIANT
// *** YOU WANT ENFORCED *** - which for a knowledge graph it usually
// is - and anonymous traversals for AD-HOC ANALYSIS and where you
// DELIBERATELY want an edge type to span collections the definition
// would forbid.
// ==================================================================
// TRAVERSAL - and the one feature that matters most: *** PRUNE. ***
// ==================================================================
FOR v, e, p IN 1..3 OUTBOUND "entity/acme-corp" GRAPH "knowledge"
RETURN { name: v.name, via: e.type, depth: LENGTH(p.edges) }
// v = VERTEX, e = EDGE, p = THE WHOLE PATH
// OUTBOUND | INBOUND | ANY
// *** FILTER discards paths AFTER THEY HAVE BEEN WALKED: ***
FOR v, e, p IN 1..3 OUTBOUND "entity/acme-corp" GRAPH "knowledge"
FILTER v.kind == "organisation"
RETURN v.name // 2,100 ms
// *** PRUNE STOPS THE DESCENT, SO THE PATHS BELOW ARE NEVER WALKED
// *** AT ALL: ***
FOR v, e, p IN 1..3 OUTBOUND "entity/acme-corp" GRAPH "knowledge"
PRUNE v.kind != "organisation"
FILTER v.kind == "organisation"
RETURN v.name // *** 31 ms ***
//
// *** ON A DENSE GRAPH THAT IS THE DIFFERENCE BETWEEN A FAST QUERY
// *** AND AN INCIDENT. *** Module 4 covers it properly - *** START
// *** USING IT NOW, because retrofitting it means re-reasoning about
// *** every traversal you wrote. ***
Discussion
No questions on this topic yet. Sign in to ask the first one.