Schema Reference
A rhypedb schema is a text file (conventionally *.rhype) that declares your object types, their fields, and the relationships between them. The server reads it at startup (--schema), and it is the single source of truth for what the database will store and enforce.
type User {
name: String
email: String @unique
age: u32
friends: [User] @on_delete(remove)
posts: [Post] @inverse(Post.author)
embedding: Vector<384> @vectorize(source: "name", model: "all-MiniLM-L6-v2")
}
Types
A schema is a collection of type declarations. Each type has a name (used as-is in queries) and a brace-delimited block of fields:
type TypeName {
field_name: FieldType
another_field: FieldType @directive
}
Fields are separated by whitespace — write one per line. (Commas are not used between top-level fields, though an edge-field block accepts them.) Field names may not contain a double underscore (__) — that sequence is reserved for the engine's internal sidecar keys.
Object identity
Every object has an id — a database-assigned unsigned 64-bit integer that is its primary key. You don't declare it; every type has one implicitly.
- Assigned on
create. ids come from a counter and increase monotonically. You can't set or override an object's id when creating it. - Globally unique, not per-type. The counter is shared across all types, so a
Userand aPostcreated in sequence get different ids (e.g.1and2) — ids are unique across the whole database, not1..Nwithin each type. - Never reused. Deleting an object does not recycle its id; the counter only moves forward (it is re-seeded past the highest existing id when the database reopens).
You reference objects by id in queries. A relation field in a create takes the target's id as a plain integer:
User.get(1)
Post.create({ title: "Hello", author: 1 })
ids on the wire
In a POST /query response an object is shaped as { "type": …, "id": …, "fields": { … } }, with id as a JSON number:
{ "object": { "type": "User", "id": 1, "fields": { "name": "Alice" } } }
Because JSON numbers are IEEE-754 doubles in most clients, an id above 2⁵³ can lose precision if parsed as a number — treat ids as opaque identifiers, and in languages where it matters read them as 64-bit integers. (The logical export format encodes ids as strings precisely so a dump round-trips exactly.)
There is no user-defined auto-increment, default, or sequence for your own scalar fields — the object
idis the only auto-assigned value.@uniqueenforces uniqueness on values you supply (e.g.
Field types
Scalars
| Type | Meaning | Written as | Reads back as |
|---|---|---|---|
String | UTF-8 text | "text" | string |
Bool | boolean | true / false | boolean |
i32, i64 | signed integers | 42 | number |
u32, u64 | unsigned integers | 42 | number |
f32, f64 | floating point | 1.5 | number |
DateTime | timestamp (epoch-millis UTC) | RFC 3339 string "2026-06-20T12:00:00Z", or an integer epoch-millis | RFC 3339 string |
Bytes | raw byte blob | base64 string "aGVsbG8=" | base64 string |
Json | arbitrary JSON value | a raw JSON literal { "k": 1 } (or any scalar) | inline JSON |
Note the casing: the named types (
String,Bool,DateTime,Bytes,Json) are capitalized, while the numeric primitives (i64,u32,f64, …) are lowercase. This matches how you refer to them in queries and migrations.
DateTime is stored as a 64-bit epoch-millisecond timestamp (UTC); sub-millisecond precision in an RFC 3339 input is truncated. It is filterable and orderable (.filter(.created > "2026-01-01T00:00:00Z") works against either an RFC 3339 string or an integer epoch-millis), including pre-epoch (negative) timestamps. Mark it @indexed to build an ordered secondary index so range queries skip the full scan; @unique enforces an exact-match uniqueness constraint.
Bytes is an arbitrary byte blob, written and read as standard base64. From the query language it is not filterable beyond presence checks (== null / != null); any other comparison on a Bytes field is rejected with an error (the query syntax has no Bytes literal, and byte-ordering a blob is not a meaningful user query). Programmatic callers can still match exact or ranged byte values via the engine API Database::filter_scan_bytes (which uses a @indexed byte index when present).
Json holds an arbitrary JSON value. It supports whole-value equality filtering only (==/!= against a complete JSON literal). Ordering comparisons (<, >, …) are rejected (no total order over arbitrary JSON), and querying into a key or path (e.g. .meta.k == 1) is not supported yet — both are rejected with an error rather than silently matching nothing. @indexed is not supported on Json (use @unique for an exact-match constraint).
Relations
A field whose type is another type name is a relationship:
author: User // to-one
posts: [Post] // to-many
Relationships are stored and traversed by the database — there are no foreign-key columns or junction tables in your schema. You create and remove links at query time with .link(...) / .unlink(...) (see the Query Language).
Vectors
embedding: Vector<384>
Vector<N> declares an N-dimensional float vector. On its own it stores raw vectors you supply; add an @index(hnsw, ...) directive to make it searchable and @vectorize(...) to have the server compute embeddings for you. See Vector Search.
Edge fields (metadata on relationships)
A relationship can carry its own scalar fields — data that belongs to the link, not to either object. Declare them in a block after the relation:
type User {
favorite_movies: [Movie] {
rating: f32
added_at: DateTime
}
}
You set edge fields when linking, from the source object: User.get(1).link(.favorite_movies, Movie.get(42), { rating: 4.5 }). (Naming .favorite_movies is optional when it is the only field of User that points to Movie; see Links.)
Directives
Directives annotate a field with @name or @name(args).
@unique
On a scalar field, enforces that no two objects of the type share a value. A violating insert is rejected atomically.
email: String @unique
@indexed
On a scalar field, builds a secondary index so filter queries on that field don't scan the whole type. Use it for fields you filter or look up by frequently.
year: i64 @indexed
Each indexed field adds one index entry per object. For small objects that entry also holds a copy of the object, so an indexed query returns rows without a second lookup; see Storage cost of indexes and relations.
@indexed(cover: false)
The same index without the copies: each entry holds only the field's value and the object's id, and a query fetches each matching object by id.
seen: Bool @indexed(cover: false)
Use it on a field whose index is large and that you rarely read in full, such as a Bool flag that half the objects share. With the default, three such flags on a mail store hold three extra copies of every small message. Queries return the same rows in the same order either way. Without the copies, a query that returns many rows makes one lookup per row, so it runs slower than one served from copies. cover: true is the default and the same as plain @indexed.
Type-level @index(field, ..., order [asc|desc])
On a type, declares an ordered index: the fields before the last are pinned by equality, and the last orders the rows within each group. It serves "the newest N messages in this place, then the next N" without reading the rest of the place:
type Message @index(place, created desc) {
place: String
created: DateTime
body: String
}
Message.filter(.place == "lobby").order_by(.created, desc).limit(50)
A page through the index reads about limit + 1 entries (the extra one tells whether another page exists) and fetches only the rows it returns, however many objects the group holds. See Ordering and pages.
- Fields. Any scalar but
Json, each named once. Only the last field takesasc(the default) ordesc. A type may declare several indexes, each with a different field list or direction;@index(at)with no equality fields orders the whole type. - Which queries use it. A query is served by an index when it is
TypeorType.filter(...)(plus more.filtersteps), every equality field of the index is pinned by a top-level==in the filter, and.order_bynames the index's last field in its direction. Other conjuncts (&&),||branches and further filters are checked on each row the index yields. Any other ordered query is still answered, by sorting the rows its pipeline produces, with the same order and cursors. Ordering in the opposite direction from the index sorts too: declare the second direction as its own index if you need it. - Order. By the field's value: integers, floats (
-0.0equals0.0; aNaNsorts by its sign, a positive one above every number and a negative one below), strings and bytes by their bytes,falsebeforetrue. A missing ornullvalue sorts first ascending and last descending. Ties are broken by id in the same direction, so the order is total and stable. - Maintenance. Every create, update and delete maintains every index of its type in its own transaction, so an index is never stale. Adding an index to a populated type (on a reopen or
POST /admin/reload) builds it from the existing objects before the database accepts requests: the work is one pass over that type, once. Removing or changing a declaration sweeps the old entries the same way. Changing the type of a field an index uses is refused; drop the index first. Likewise, a schema that adds an index over a field whose type change is still in progress is refused at open; add it once the migration completes or is cancelled.
@fulltext / @fulltext(analyzer: "simple", positions: false)
On a String field, builds a full-text inverted index so the field can be searched by keyword with Type.matches(.field, "terms", k: N) (see Queries → Full-text search). The index is maintained synchronously inside each object's transaction, like @unique and @indexed, so it is never stale and survives a crash exactly as the object does.
type Post {
title: String @fulltext
body: String @fulltext(analyzer: "simple", positions: false)
}
Parameters (both optional):
| Parameter | Default | Meaning |
|---|---|---|
analyzer | "simple" | How text is split into terms. simple: Unicode word segmentation, lowercase, diacritics folded to ASCII (Café → cafe), no stemming. english: the same, then English stop words removed (the Snowball list — the, of, my, is, don't, … 174 function words that would otherwise dominate BM25 ranking) and English stemming (Snowball/Porter2), so camera, cameras and Camera's are one term and run finds running — on indexed text and on query terms alike, phrases included. Use english for prose in English; simple for identifiers, codes, mixed-language text, or when prefix terms must complete character by character (a stemmed index holds stems, so securit* does not find security, stored as secur). The analyzer is part of the index; changing it — or upgrading to a release that changes what an analyzer does, as adding stop words to english did — rebuilds the index. |
positions | true | Store term positions. Required for phrase queries ("distributed consensus"); costs roughly the size of the text again. positions: false halves the index and makes a phrase query on the field an error. |
Only the first 65 536 words of a value are indexed; text past that is stored but not searchable. The words a create or update will index count against the query governor's examined-rows budget (an update, once per object it changes), so an oversized value is refused rather than indexed. This cap arrived with a change to what both analyzers do, so an index built by an earlier release is rebuilt in the background on the first open after upgrading.
@fulltext stacks with @unique and @indexed. It is rejected on any non-String field. Substring matching without an index is a separate predicate: .filter(.title.contains("invoice")) works on every String field.
Adding, changing or removing the directive on existing data. Unlike @indexed, @fulltext backfills: adding it to a populated type (on a reopen or POST /admin/reload) starts a background build of the index for every existing object; changing analyzer or positions rebuilds the index into a fresh generation and sweeps the old rows; removing the directive drops the index. New writes are indexed immediately throughout. While a build is running, .matches on that field returns an error carrying the progress, and GET /status reports it under fulltext (see Running rhypedb). A build interrupted by a restart resumes where it left off.
@on_delete(policy)
On a relationship, declares what happens to the link (and possibly the target) when an object is deleted. Policies:
| Policy | Behavior |
|---|---|
remove | Remove the link only; leave the target object. |
cascade | Delete the target object too (recursively). |
deny | Refuse the delete while the link exists. |
posts: [Post] @on_delete(cascade)
friends: [User] @on_delete(remove)
@inverse(Type.field)
Marks two relationship fields as the two ends of a single bidirectional relationship. Linking one side makes the other side reflect it automatically.
type User {
posts: [Post] @inverse(Post.author)
}
type Post {
author: User
}
@index(hnsw, ...)
On a Vector<N> field, configures the HNSW index used for similarity search. All parameters are optional and have defaults.
embedding: Vector<768> @index(hnsw, metric: cosine, quantization: turboquant_4bit, m: 16, ef_construction: 200)
| Parameter | Values | Default |
|---|---|---|
metric | cosine, l2, dot_product | cosine |
quantization | turboquant_2bit, turboquant_3bit, turboquant_4bit | turboquant_4bit |
m | HNSW graph fan-out (≥ 1) | engine default |
ef_construction | build-time search width (≥ 1) | engine default |
Fewer quantization bits means a smaller index and faster search at some recall cost; pair it with per-query rerank (see Vector Search) to recover precision. quantization: none is rejected — vectors are always quantized in the index (the raw vectors are still kept losslessly at rest).
@vectorize(source, model)
On a Vector<N> field, tells the server to compute the embedding for you from a String field on the same object whenever it is created or updated.
text: String
embedding: Vector<384> @vectorize(source: "text", model: "all-MiniLM-L6-v2")
source— the name of aStringfield on this type.model— the embedding model identifier (e.g.all-MiniLM-L6-v2). The vector dimensionNmust match the model's output size.
Combine it with @index(hnsw, ...) on the same field to both auto-embed and index. See Vector Search.
Storage cost of indexes and relations
rhypedb keeps each object once, under its id. Two read-path caches can add copies, and both are bounded by size:
-
@indexedfields. Every indexed field writes one index entry per object (key: field value + id). If the object serializes to at most 1 KiB, the entry also carries a copy of it, sofilteron that field returns rows straight from the index. A larger object's entry carries only the key, as does every entry of an@indexed(cover: false)field; the query fetches the object by id, one point lookup per row. Results and their order are the same either way. -
To-one relations. A link's reverse entry (what
@inversetraversals walk) holds the ids of the linking object's other to-one targets, plus a copy of each such target that is at most 1 KiB, so a hop likeMovie.ratings.usercan return users without looking each one up. The linking object's own fields are never copied there, so a large type with many to-many links (a mail message with labels and recipients, say) costs a few dozen bytes per link. -
Type-level
@index(...). One entry per object per declared index. The entry holds no copy of the object: its key is the index's field values plus the id, and its value is empty. A page fetches its rows by id.
So a text-heavy type costs about its own size plus small per-index and per-link entries. Embedded users can move the threshold with OpenOptions::cover_max_bytes (usize::MAX copies everything, 0 nothing); the server uses the default. A new threshold, or a field switched to or from cover: false, applies to entries written from then on. Entries written by older versions (before 2026-11), under an earlier threshold, or before the switch keep their old form until rewritten. To bring a whole database up to the current rules at once, embedded users call Database::rewrite_covers() and then compact (db.storage().compact()). The pass runs in small batches alongside normal traffic and is safe to interrupt and rerun. On a 2.2 GB mail store it cut reverse-entry data from 333 MB to 136 MB.
Those stored target ids have to stay in step with the links themselves. Versions before 2026-11 let them drift: a reverse entry written before the object's other to-one link existed never learned about that link, and relinking or unlinking a to-one relation left the old id in the object's other reverse entries. A hop like Movie.ratings.user could then miss targets or return the old one. Current versions keep the ids in step on every link, unlink and delete. A database that an older version wrote with links in it starts out distrusted: Database::cover_peers_sound() returns false, and to-one hops read the links themselves instead of the stored ids. Results are correct, but those hops lose the shortcut. One rewrite_covers() run repairs the stored ids and records that the database can be trusted again; that record persists across restarts. New databases are trusted from the start.
A complete example
type User {
name: String
email: String @unique
reputation: u32 @indexed
friends: [User] @on_delete(remove)
posts: [Post] @inverse(Post.author) @on_delete(remove)
favorite_movies: [Movie] {
rating: f32
added_at: DateTime
}
}
type Post {
title: String
body: String
author: User @on_delete(cascade)
tags: [Tag] @on_delete(remove)
embedding: Vector<384> @vectorize(source: "body", model: "all-MiniLM-L6-v2") @index(hnsw, metric: cosine)
}
type Movie {
title: String
year: i64 @indexed
}
type Tag {
name: String @unique
}
Evolving the schema
Changing the schema of a database that already holds data is a real operation with rules — adding fields is free, removing them is gated, and renames or type changes go through a migration system. See Schema Migrations.