Tables are schemaless by default and that default deserves a decision rather than acceptance. A schemaless table accepts any field, which is pleasant while you are exploring and means a typo creates a field - asignee sits quietly next to assignee, and the query filtering on the correct spelling silently returns nothing. A schemafull table, declared with DEFINE TABLE ... SCHEMAFULL plus DEFINE FIELD for each field, rejects anything undeclared.
The recommendation this course makes: schemafull for anything with invariants, schemaless for genuinely open payloads, and both in the same database is normal. Core entities - users, projects, tasks, memberships - are schemafull, because they have types and constraints that are worth enforcing in one place rather than in every writer. Attachment metadata, integration payloads and user-defined custom fields are schemaless, because that is their nature.
DEFINE FIELD gives you more than a type. It carries a TYPE including option<> for nullable and record<table> for a typed link, a DEFAULT, an ASSERT expression that must hold, a VALUE expression that computes the field on write, and its own PERMISSIONS. ASSERT is the one to use aggressively - an email shape, a state drawn from a fixed set, points within a range. Those are the invariants your application would otherwise check in several places and eventually forget in one.
Now the modelling decision at the centre of this module: a record link or a graph edge?
A link is a field holding a record identifier. It is a direct pointer, traversal is a dot, and it is the right choice when the relationship is an attribute of the record and carries no data of its own - a task's assignee, a task's project, a comment's author. Cheap, simple, obvious in the data.
A graph edge, created with RELATE, is itself a record in an edge table with its own fields. RELATE user:ashton->assigned->task:01HQ3M SET at = time::now(), by = user:dana creates a record you can query, filter and aggregate. It is the right choice when the relationship has properties, or has a history, or is one of many of the same kind between the same two records - who assigned whom and when, a dependency with a type, a review with a verdict and a timestamp.
The decision rule, which is worth stating plainly: if you would ever want to ask a question about the relationship itself, make it an edge. A link can only answer questions about its endpoints. Converting a link into an edge later means rewriting the data and every query that touched it, so the cost of getting this wrong is real - and the cost of over-using edges is that simple attribute lookups become traversals, which are more expensive and less obvious. Most schemas want both, and the split is usually clean once you apply the rule.
Traversal syntax is where SurrealQL earns its multi-model claim. ->edge->table goes out, <-edge<-table comes back, you can chain them, filter at each hop, and traverse an edge's own fields on the way through. A two-hop query that would be a pair of joins and a subquery in SQL is one readable expression here, and that genuinely is the feature.
Indexes are declared and they matter more than usual, because the planner will not compensate for their absence. DEFINE INDEX on a field or a set of fields; UNIQUE to enforce uniqueness, which is also the cleanest way to express a real constraint; and specialised index types for full-text search and vectors, covered in Module 4. Verify that your index is actually used rather than assuming it - that is entry four in your version behaviour log, and it is worth re-checking after every upgrade.
Laboratory exercise 2 - two models, measured.
Design two competing models for the project tracker. The contrast that matters here: one that uses links for everything including assignment, task dependencies and project membership; and one that uses edges for every relationship that carries data - assignment with who and when, dependencies with a type, membership with a role and a date.
Implement both, schemafull where there are invariants, and load at least 5 million records with realistic graph density into each.
Implement a common set of queries against both and record latency for each: a task with its assignee and project; every open task in a project with assignees; a user's assigned tasks across projects; the full dependency chain of a task; tasks blocked by an unfinished dependency; who assigned a given task and when; the activity stream for a project; and membership with roles for a project. Mark which queries the links-only model simply cannot answer - that list is the decision rule made concrete.
Verify your constraints actually constrain. For every ASSERT, TYPE and UNIQUE you declared, write a test that violates it and confirm rejection. Include a test that writes a misspelled field to a schemaless table and to a schemafull one, and record the difference - that is the demonstration that justifies the schemafull default for core entities.
Then the index study: baseline with no secondary indexes, then add them one at a time, recording query latency and write throughput at each step, and using EXPLAIN to confirm each index is being used. Record any case where a declared index was not used, because that is a finding.
Deliverable: both models with their schema definitions, the query set timed against both with the unanswerable queries marked, the constraint violation tests all passing, the misspelled-field demonstration, the index study with EXPLAIN evidence, and a page arguing for one model with the measurements behind it.
-- ==================================================================
-- *** SCHEMALESS IS THE DEFAULT, AND THE DEFAULT DESERVES A DECISION
-- *** RATHER THAN ACCEPTANCE. ***
-- ==================================================================
-- SCHEMALESS: accepts ANY field. Pleasant while exploring - and
-- *** A TYPO CREATES A FIELD: ***
CREATE task:bad SET asignee = user:ashton; -- *** accepted ***
SELECT * FROM task WHERE assignee = user:ashton; -- *** MISSES IT ***
-- No error. No warning. The record is simply invisible to every
-- query that spells the field correctly.
-- SCHEMAFULL: rejects anything undeclared.
DEFINE TABLE task SCHEMAFULL;
DEFINE FIELD title ON task TYPE string
ASSERT string::len($value) BETWEEN 1 AND 200;
DEFINE FIELD project ON task TYPE record<project>; -- a TYPED link
DEFINE FIELD assignee ON task TYPE option<record<user>>; -- nullable
DEFINE FIELD watchers ON task TYPE option<array<record<user>>>;
DEFINE FIELD state ON task TYPE string DEFAULT "todo"
ASSERT $value IN ["todo","in_progress","blocked","review","done"];
DEFINE FIELD points ON task TYPE option<int>
ASSERT $value = NONE OR $value BETWEEN 0 AND 21;
DEFINE FIELD created ON task TYPE datetime VALUE time::now() READONLY;
DEFINE FIELD updated ON task TYPE datetime VALUE time::now();
-- *** VALUE COMPUTES THE FIELD ON WRITE *** - `updated` can
-- no longer be forgotten by a writer, which is the point.
DEFINE FIELD meta ON task FLEXIBLE TYPE option<object>;
-- *** one schemaless island inside a schemafull table ***
CREATE task:bad2 SET asignee = user:ashton;
-- -> *** Found 'asignee' which is not a defined field. REJECTED. ***
-- *** THE RECOMMENDATION: SCHEMAFULL FOR ANYTHING WITH INVARIANTS,
-- *** SCHEMALESS FOR GENUINELY OPEN PAYLOADS. Both in one database
-- *** is normal: ***
-- SCHEMAFULL user, project, task, membership, comment
-- SCHEMALESS attachment_meta, integration_payload, custom_fields
--
-- *** USE ASSERT AGGRESSIVELY. *** Those are the invariants your
-- application would otherwise check in several places and
-- eventually forget in one:
DEFINE FIELD email ON user TYPE string
ASSERT string::is::email($value);
DEFINE INDEX user_email ON user FIELDS email UNIQUE;
-- And TEST EVERY ONE OF THEM. A declared constraint you have not
-- seen reject something is a guess.
-- ==================================================================
-- *** THE MODELLING DECISION AT THE CENTRE OF THIS MODULE:
-- *** A RECORD LINK OR A GRAPH EDGE? ***
-- ==================================================================
-- A LINK is a field holding a record identifier. A DIRECT POINTER.
-- *** RIGHT WHEN THE RELATIONSHIP IS AN ATTRIBUTE OF THE RECORD AND
-- *** CARRIES NO DATA OF ITS OWN: ***
-- task.assignee task.project comment.author
SELECT title, assignee.name FROM task WHERE project = project:atlas;
-- An EDGE, created with RELATE, is *** ITSELF A RECORD IN AN EDGE
-- TABLE WITH ITS OWN FIELDS: ***
RELATE user:ashton->assigned->task:01HQ3M
SET at = time::now(), by = user:dana, note = "sprint 14";
RELATE task:01HQ3M->depends_on->task:01HQ2A
SET kind = "blocks", added = time::now(), added_by = user:dana;
RELATE user:dana->member_of->project:atlas
SET role = "reviewer", since = time::now();
-- *** RIGHT WHEN THE RELATIONSHIP HAS PROPERTIES, OR A HISTORY, OR
-- *** IS ONE OF MANY OF THE SAME KIND BETWEEN THE SAME TWO
-- *** RECORDS. ***
--
-- *** THE DECISION RULE, PLAINLY: IF YOU WOULD EVER WANT TO ASK A
-- *** QUESTION ABOUT THE RELATIONSHIP ITSELF, MAKE IT AN EDGE. ***
-- A LINK CAN ONLY ANSWER QUESTIONS ABOUT ITS ENDPOINTS:
SELECT in.name AS assigner, out.title AS task, at, note
FROM assigned WHERE at > time::now() - 7d ORDER BY at DESC;
-- *** THE LINKS-ONLY MODEL CANNOT ANSWER THAT AT ALL. ***
--
-- And the cost of each mistake, so the rule has teeth:
-- LINK where you needed an EDGE -> rewrite the data AND every
-- query that touched it.
-- EDGE where a LINK would do -> simple attribute lookups
-- become TRAVERSALS: more expensive, and less obvious in the
-- data.
-- *** MOST SCHEMAS WANT BOTH, AND THE SPLIT IS USUALLY CLEAN ONCE
-- *** YOU APPLY THE RULE. ***
-- ==================================================================
-- TRAVERSAL - where SurrealQL earns its multi-model claim.
-- ==================================================================
-- ->edge->table OUT <-edge<-table BACK
SELECT ->assigned->task.title AS tasks FROM user:ashton;
SELECT <-assigned<-user.name AS assigners FROM task:01HQ3M;
-- CHAINED, FILTERED AT EACH HOP:
SELECT title,
->depends_on->task.title AS blocks,
<-depends_on<-task.title AS blocked_by
FROM task WHERE project = project:atlas AND state != "done";
-- Tasks blocked by something UNFINISHED - two hops with a filter:
SELECT title FROM task
WHERE project = project:atlas
AND count(->depends_on->task[WHERE state != "done"]) > 0;
-- A project's members WITH THEIR ROLES - the edge's own field:
SELECT in.name AS member, role, since
FROM member_of WHERE out = project:atlas ORDER BY role;
-- Traverse THROUGH an edge's fields on the way:
SELECT ->assigned[WHERE at > time::now() - 30d]->task.title AS recent
FROM user:ashton;
--
-- *** A TWO-HOP QUERY THAT WOULD BE A PAIR OF JOINS AND A SUBQUERY
-- *** IN SQL IS ONE READABLE EXPRESSION HERE. THAT GENUINELY IS THE
-- *** FEATURE. ***
-- ==================================================================
-- *** INDEXES MATTER MORE THAN USUAL, BECAUSE THE PLANNER WILL NOT
-- *** COMPENSATE FOR THEIR ABSENCE. ***
-- ==================================================================
DEFINE INDEX task_project_state ON task FIELDS project, state;
DEFINE INDEX task_assignee ON task FIELDS assignee;
DEFINE INDEX user_email ON user FIELDS email UNIQUE;
DEFINE INDEX membership_unique ON member_of FIELDS in, out UNIQUE;
-- *** UNIQUE IS ALSO THE CLEANEST WAY TO EXPRESS A REAL
-- *** CONSTRAINT *** - one membership per user per project, said
-- once, in the schema.
-- *** VERIFY THE INDEX IS ACTUALLY USED RATHER THAN ASSUMING IT: ***
SELECT * FROM task WHERE project = project:atlas AND state = "todo"
EXPLAIN;
-- look for an Iterate Index operation naming task_project_state.
-- An Iterate Table means *** YOUR INDEX IS NOT BEING USED *** -
-- which is entry four in your version behaviour log, and *** WORTH
-- RE-CHECKING AFTER EVERY UPGRADE. *** Record any case where a
-- declared index was not used: that is a finding, not a mystery.
INFO FOR TABLE task; -- fields, indexes, events, permissions
Discussion
No questions on this topic yet. Sign in to ask the first one.