Collections, Documents, Edges, arangosh and AQL Basics

Article · 9:00

Document and edge collections, the key and identifier scheme, AQL fundamentals, the two deployments, and the limits that matter.

There are two kinds of collection and the distinction is structural. A document collection holds JSON documents. An edge collection holds documents too, with two mandatory attributes - _from and _to, each a full document identifier - and an automatic index on both, which is what makes traversal fast. An edge is a document, so an edge carries properties as naturally as any other record, and you query an edge collection directly when you want to ask about the relationships rather than traverse them.

Three system attributes matter. _key is the document's key within its collection, unique there, and you may supply it - which is the single most useful fact in this topic, because a deterministic key gives you idempotent writes. _id is collection/key, globally unique, and it is what _from and _to hold. _rev is a revision token that changes on every modification, and it is how you do optimistic concurrency: pass the _rev you read and the write fails if someone else changed the document first.

AQL is a declarative language built around FOR ... IN and it reads more like a comprehension than like SQL. FOR doc IN collection FILTER ... SORT ... LIMIT ... RETURN .... A join is a nested FOR with a FILTER that relates them, or - more often and more cheaply - a direct DOCUMENT() lookup when you have the identifier. Aggregation is COLLECT ... AGGREGATE. Objects and arrays are native, so projecting a nested structure is just writing the shape you want in the RETURN. The thing to appreciate early is that one AQL query can do a document filter, a graph traversal, a search ranking and an aggregation together, and that composability is the reason to use this engine rather than three.

Stand up both deployments now. A single server is one process and is where you develop. A cluster is coordinators, which are stateless and accept queries; DB-Servers, which hold the shards; and an agency, a Raft-based configuration store that is always three or five agents. The reason you need both from day one is that this course's most consequential measurements are the difference between them - and specifically that graph traversal behaves differently, for reasons Module 5 explains and Module 4 measures.

The limits to know now. Single-document operations are atomic, always, which is a strong and useful guarantee; multi-document transactions exist with real constraints, covered in Module 3. ArangoSearch views are eventually consistent - a just-inserted document is not immediately searchable. UPSERT is not safe against concurrency without a unique index on the attributes it looks up, which is the next topic and is a genuine correctness trap. A query can exhaust memory and the protection is a configured limit, not good behaviour. And the licence for recent Community Edition versions is source-available rather than permissive, with terms varying by version - so read the licence for the version you intend to deploy, and have someone qualified review it, before you build on it.

Laboratory exercise 1 - two deployments, one generator, both numbers.

Stand up both a single server and a three-DB-Server cluster with three agents and two coordinators. Record versions, topology and configuration for each. Verify you can reach both from your client.

Write the knowledge graph dataset generator that the rest of the course depends on: entities of at least five types, typed relationships with properties, documents with substantial realistic text attached to entities, and configurable scale and graph density. The text must be real enough to search and the density real enough to make traversal numbers mean something.

Load at least 20 million documents and 60 million edges into both deployments.

Then establish the practice this course runs on: write ten representative queries - document lookups, filters, aggregations and a two-hop traversal - and run every one on both deployments, recording both numbers. Note which queries differ and by how much. That table is your first evidence that topology matters, and you will extend it in Module 4.

Demonstrate the three system attributes: supply your own _key and show the write is idempotent; show _id is what an edge's _from holds; and do an optimistic concurrency cycle with _rev, including the failure when the revision has moved.

Demonstrate the search consistency default: insert a document, immediately search for it, and show it missing. Then wait and show it found. Record the delay. That five-minute experiment prevents a class of bug that is otherwise maddening.

Deliverable: both deployments documented, the generator as reusable code, both datasets loaded, the ten-query two-deployment comparison table, the system attribute demonstrations, the search consistency demonstration with its measured delay, and a note recording the licence of the version you deployed and whether it has been reviewed.

// ==================================================================
// TWO KINDS OF COLLECTION. The distinction is STRUCTURAL.
// ==================================================================
//   arangosh> db._create("entity");                 // DOCUMENT
//   arangosh> db._createEdgeCollection("relates");  // EDGE
//
// An EDGE COLLECTION holds documents too, with TWO MANDATORY
// attributes - _from and _to, each a FULL DOCUMENT IDENTIFIER - and
// *** AN AUTOMATIC INDEX ON BOTH, WHICH IS WHAT MAKES TRAVERSAL
// *** FAST. ***
//
// *** AN EDGE IS A DOCUMENT, SO IT CARRIES PROPERTIES AS NATURALLY
// *** AS ANY OTHER RECORD *** - and you query an edge collection
// DIRECTLY when you want to ask about the RELATIONSHIPS rather than
// TRAVERSE them.

// ==================================================================
// THREE SYSTEM ATTRIBUTES.
// ==================================================================
//   {
//     "_key": "acme-corp",                  // unique IN ITS
//                                           // COLLECTION, and
//                                           // *** YOU MAY SUPPLY
//                                           // *** IT ***
//     "_id":  "entity/acme-corp",            // collection/key,
//                                           // GLOBALLY unique.
//                                           // *** WHAT _from AND
//                                           // *** _to HOLD. ***
//     "_rev": "_gXyZ1aB---",                 // changes on EVERY
//                                           // modification
//     "name": "Acme Corporation",
//     "kind": "organisation"
//   }
//
// *** SUPPLYING _key IS THE SINGLE MOST USEFUL FACT HERE, BECAUSE A
// *** DETERMINISTIC KEY GIVES YOU IDEMPOTENT WRITES: ***
INSERT { _key: "acme-corp", name: "Acme Corporation",
         kind: "organisation" }
  INTO entity OPTIONS { overwriteMode: "update" }
//   -> run it twice, ONE document. The same property the time-series
//      and multi-model courses relied on, available by choosing the
//      key rather than generating one.

// _rev IS HOW YOU DO OPTIMISTIC CONCURRENCY - pass the _rev you
// READ, and the write FAILS if someone else changed it first:
UPDATE { _key: "acme-corp", _rev: @rev, status: "verified" }
  IN entity OPTIONS { ignoreRevs: false }
//   -> ERROR_ARANGO_CONFLICT (1200) if the revision has moved.
//   *** ignoreRevs DEFAULTS TO true, which means the check is OFF
//   *** UNLESS YOU ASK FOR IT. *** A lost update is the default
//   behaviour; opt in.

// ==================================================================
// AQL: declarative, built around FOR ... IN. Reads like a
// comprehension, not like SQL.
// ==================================================================
FOR e IN entity
  FILTER e.kind == "organisation" AND e.founded >= 2000
  SORT e.name
  LIMIT 50
  RETURN { id: e._key, name: e.name, founded: e.founded }

// A JOIN - a nested FOR with a relating FILTER:
FOR d IN document
  FOR e IN entity
    FILTER e._id == d.about
    RETURN { title: d.title, entity: e.name }

// *** MORE OFTEN AND MORE CHEAPLY, a direct DOCUMENT() lookup when
// *** you have the identifier - a primary index hit, not a join: ***
FOR d IN document
  FILTER d.published >= "2026-01-01"
  RETURN { title: d.title, entity: DOCUMENT(d.about).name }

// AGGREGATION:
FOR e IN entity
  COLLECT kind = e.kind INTO group
  AGGREGATE n = COUNT(1), newest = MAX(e.founded)
  SORT n DESC
  RETURN { kind, n, newest }

// *** AND THE THING TO APPRECIATE EARLY: ONE AQL QUERY CAN DO A
// *** DOCUMENT FILTER, A GRAPH TRAVERSAL, A SEARCH RANKING AND AN
// *** AGGREGATION TOGETHER *** - that composability is the reason to
// use this engine rather than three:
FOR d IN doc_view
  SEARCH ANALYZER(d.body IN TOKENS("supply chain risk", "text_en"),
                  "text_en")
  LET score = BM25(d)
  LET subject = DOCUMENT(d.about)
  LET related = (
    FOR v IN 1..2 OUTBOUND subject relates
      FILTER v.kind == "organisation"
      LIMIT 5 RETURN v.name
  )
  SORT score DESC LIMIT 20
  RETURN { title: d.title, score, subject: subject.name, related }
//   Search + document lookup + traversal + ranking, ONE STATEMENT,
//   ONE ROUND TRIP. That is the product.

// ==================================================================
// *** STAND UP BOTH DEPLOYMENTS NOW. NOT OPTIONAL IN THIS COURSE. ***
// ==================================================================
//   SINGLE SERVER   one process. Where you DEVELOP.
//
//   CLUSTER:
//     *** COORDINATORS *** stateless; ACCEPT QUERIES; scale with
//                          query CONCURRENCY
//     *** DB-SERVERS ***   hold the SHARDS; scale with DATA
//     *** AGENCY ***       a RAFT-based configuration store.
//                          ALWAYS 3 OR 5 AGENTS. Not 2, not 4.
//
// *** THE REASON YOU NEED BOTH FROM DAY ONE: THIS COURSE'S MOST
// *** CONSEQUENTIAL MEASUREMENTS ARE THE DIFFERENCE BETWEEN THEM ***
// - and specifically that GRAPH TRAVERSAL BEHAVES DIFFERENTLY, for
// reasons Module 5 explains and Module 4 measures.
//
// *** THE PRACTICE THIS COURSE RUNS ON: RUN EVERY GRAPH QUERY ON
// *** BOTH AND RECORD BOTH NUMBERS. *** The single-server number says
// whether the QUERY IS WELL WRITTEN. The cluster number says whether
// it WILL WORK IN PRODUCTION. Different questions - and measuring
// only one is how teams get surprised late.
//
//   db._engineStats();  db._version();
//   // cluster health, from a coordinator:
//   //   GET /_admin/cluster/health

// ==================================================================
// *** THE LIMITS TO KNOW NOW. ***
// ==================================================================
//   * *** SINGLE-DOCUMENT OPERATIONS ARE ATOMIC, ALWAYS. *** A
//     strong and useful guarantee - build on it where you can.
//     Multi-document transactions exist WITH REAL CONSTRAINTS
//     (Module 3).
//   * *** ARANGOSEARCH VIEWS ARE EVENTUALLY CONSISTENT. *** A
//     just-inserted document is NOT IMMEDIATELY SEARCHABLE.
//     *** DEMONSTRATE THIS IN FIVE MINUTES; it prevents a class of
//     bug that is otherwise maddening. ***
//   * *** UPSERT IS NOT SAFE AGAINST CONCURRENCY WITHOUT A UNIQUE
//     *** INDEX *** on the attributes it looks up - the next topic,
//     and a genuine CORRECTNESS trap, not a performance one.
//   * a query can EXHAUST MEMORY, and *** THE PROTECTION IS A
//     CONFIGURED LIMIT, NOT GOOD BEHAVIOUR *** (Module 4).
//   * *** GRAPH TRAVERSAL IN A SHARDED CLUSTER IS A DIFFERENT
//     *** PERFORMANCE PROPOSITION *** - and the fixes (SmartGraphs,
//     OneShard) ARE ENTERPRISE FEATURES. So *** "WE WILL SHARD IT
//     LATER" IS NOT A SAFE PLAN FOR A GRAPH WORKLOAD. ***
//   * *** THE LICENCE: recent Community Edition versions are
//     *** SOURCE-AVAILABLE RATHER THAN PERMISSIVE, with terms that
//     *** DIFFER BY VERSION. *** This is a PROCUREMENT AND LEGAL
//     question, not a technical footnote. *** READ THE LICENCE FOR
//     THE EXACT VERSION YOU INTEND TO DEPLOY AND HAVE SOMEONE
//     QUALIFIED REVIEW IT BEFORE YOU BUILD ON IT. *** Record in your
//     README which version you deployed and whether that review has
//     happened.

Discussion

No questions on this topic yet. Sign in to ask the first one.