Query Language
rhypedb has a single, path-based query language used for reads, writes, relationship traversal, and vector search. A query reads left to right: it starts from a source and then applies zero or more steps, each separated by a dot.
User.get(1).posts.filter(.title == "Hello").limit(10)
└─ source ─┘└ step ┘└────── step ──────────┘└─ step ─┘
You send a query as a string — via the CLI (-e '<query>' or the REPL), POST /query, or the binary TCP protocol. The result comes back as JSON. See the API Reference for response shapes.
In the examples on this page, text after // is a note for the reader. The query language has no comment syntax, so leave the notes out when you run a query.
Sources
Every query begins with one of these:
| Source | Meaning |
|---|---|
Type.get(id) | Fetch one object by numeric id. |
Type.get_many([id, ...]) | The objects of Type with these ids: missing ids are skipped, duplicates collapse, rows come back in ascending id order. |
Type.filter(predicate) | All objects of Type matching the predicate. |
Type | All objects of Type. |
Type.create({ ... }) | Create one object; returns it (with its assigned id). |
Type.create_batch([{ ... }, ...]) | Create many objects in one call. |
User.get(42)
User.get_many([42, 7, 19])
User.filter(.age >= 18)
User
User.create({ name: "Alice", email: "alice@example.com", age: 30 })
User.create_batch([{ name: "Bob" }, { name: "Carol" }])
get_many is a set source: it chains like Type.filter(...). A .filter, a traversal, .limit / .offset, a .similar or .matches (which ranks only the listed objects, so k is the true top-k within them), and the writes .update / .delete / .link / .unlink (with guarded-write semantics: an id deleted after the read is skipped, not an error) all apply to the objects it found:
User.get_many([3, 9, 12]).filter(.active == true).update({ seen: true })
Post.get_many([4, 8, 15, 16, 23, 42]).similar(.embedding, "rust", k: 3)
The order the ids are written in, and any repeats, do not matter: User.get_many([9, 3, 9]) returns user 3 then user 9. Under security rules every returned object must pass the read rule, exactly as for get (an unreadable one is dropped), and a write straight after the source is gated per object by that write's own rule, as get(id).update(...) is. Each listed id counts as one examined row against the query governor's row budget, so a list longer than that budget is refused; the request size bounds it too (16 MiB per TCP frame, the HTTP body limit for POST /query). Lists of many thousands of ids are fine.
Object ids are assigned by the server. To reference another object in a create, give the relation field that object's integer id:
Post.create({ title: "Hello", author: 1 }) // the post's author is user 1
The value is a plain id literal, not a Type.get(id) expression; the target's type comes from the field's declaration. To add links after the object exists, or to set a relationship's edge fields, use .link.
Steps
Steps transform or act on the current set of objects.
Traverse a relationship — .field
Follow a relationship field to the objects on the other side. Traversals chain:
User.get(1).posts // posts authored by user 1
User.get(1).friends.posts // posts by user 1's friends
User.get(1).posts.tags // tags on user 1's posts
Filter — .filter(predicate)
Keep only objects matching a predicate.
User.filter(.age > 18)
User.get(1).posts.filter(.title == "Hello")
Inside a predicate, .field refers to a field of the current object.
Comparison operators: ==, !=, <, <=, >, >=
Boolean operators: && (or and), || (or or), with parentheses for grouping. && binds tighter than ||.
User.filter(.age >= 18 && .active == true)
User.filter(.age < 13 || .age >= 65)
User.filter((.role == "admin" || .role == "mod") && .active == true)
Substring — .field.contains("text"): true when a String field contains the literal text. It is case-sensitive, never uses an index (the type is scanned like any other unindexed filter), and composes with the other operators. A null value never matches. Applying it to a non-String field is an error.
Post.filter(.title.contains("invoice"))
Post.filter(.published == true && .body.contains("4471"))
For ranked keyword search that does use an index, see Full-text search.
Vector similarity — .similar(.field, query, k: N, ...)
Find the nearest neighbours of a query in a Vector field. Covered in depth in Vector Search.
Post.similar(.embedding, "distributed systems", k: 10) // text query (auto-embedded)
Post.similar(.embedding, [0.1, 0.2, 0.3], k: 10) // raw vector query
Post.similar(.embedding, "databases", k: 10, ef: 200, rerank: 50)
| Argument | Meaning |
|---|---|
.field | the Vector field to search |
| query | a "text" string (requires @vectorize) or a raw [f32, ...] vector |
k: | number of results to return |
ef: | (optional) HNSW search width — higher is more accurate, slower |
rerank: | (optional) re-score this many candidates with full-precision vectors; 0/omitted = off |
.similar can also follow a filter, narrowing the candidate set first:
Post.filter(.published == true).similar(.embedding, "rust", k: 5)
.similar returns a ranked result: each object carries a score — the index's distance under the field's metric (lower is closer) — and the rows come back in rank order. When the cross-encoder scored a row it also carries a rerank_score (higher is better). See Ranked results.
Full-text search — .matches(.field, "query", k: N)
Ranked keyword search over a String field declared @fulltext (see Schema → @fulltext). Sits where .similar sits: bare on a type, or after a filter or traversal that narrows the candidates.
Post.matches(.body, "invoice 4471", k: 20)
Post.filter(.published == true).matches(.body, "distributed consensus", k: 10)
User.get(1).posts.matches(.title, "+draft budget", k: 5)
| Argument | Meaning |
|---|---|
.field | the @fulltext String field to search |
"query" | the search text (syntax below) |
k: | number of results to return (most relevant first) |
Query syntax. The text is analyzed with the field's analyzer (lowercased, diacritics folded, split into words; under analyzer: "english" also stop words dropped and the rest stemmed), then:
| Form | Meaning |
|---|---|
invoice 4471 | terms are OR-ed: a document matches if it contains any of them, and every term it contains adds to its score |
+invoice | a + prefix makes the term required |
"distributed consensus" | quoted words are a phrase: they must appear consecutively (the field must store positions — the default). Under english, a stop word inside the phrase leaves a gap the document must have too: "state of the art" searches for state followed three words later by art, so it matches state of the art but not state art |
camera* | a trailing * makes a prefix term: it matches every indexed term that starts with camera (camera, cameras, camerawork, …) and scores as one term — the type-ahead case |
+"exact phrase" cam* extra | modifiers combine: the phrase is required, the prefix and extra are optional |
Results are ranked by BM25 (k1 = 1.2, b = 0.75): rarer terms count more, repeated terms count more with diminishing returns, and shorter documents win ties. Each returned object carries its score (higher is better) — see Ranked results.
A prefix term is analyzed like any other term before it is expanded — lowercased and folded, and under the english analyzer stemmed: cameras* searches for the stem camera, which is what the index holds. Be aware of what that means for type-ahead over a stemmed field: the index stores stems, which are often shorter than the word being typed, so a partial word that runs past the stem finds nothing until the word is complete (securit* matches nothing because security is indexed as secur; secur* and security* both match), and a prefix the stemmer shortens matches a little more than typed (agre* searches agr*). Stemming the prefix is still the better single strategy (a dictionary sweep found it matches more partial prefixes than leaving the prefix unstemmed, and it is what makes cameras* find camera), but if you need character-by-character completion, put it on a simple field. Text that analyzes to several words before the * (e-mail*) gives ordinary terms for all but the last, which becomes the prefix.
The prefix needs at least two characters after analysis (* and c* are errors — the error names the analyzed word, so 東京*, one ideograph per word under Unicode segmentation, reports the one-character prefix 京), it cannot appear inside a phrase, and an expansion of more than 64 distinct indexed terms is refused with an error asking for a longer prefix — so a one- or two-letter prefix over a large vocabulary fails fast instead of scanning half the index. The cap counts the field's whole vocabulary under the prefix, not only the terms of the candidates a preceding filter narrowed to (under security rules it counts only terms in documents the caller may read — see below). A * anywhere but the end of a word is ordinary punctuation and splits the word.
Under english, stop words are dropped from the query exactly as from the index: of my house searches for house, +of requires nothing, and a query made only of stop words (of the) returns an empty result rather than an error. A prefix term whose text is a stop word (the*, of*) is dropped the same way rather than expanded to theory, theatre, office, … — a type-ahead client sees no results at the and results again at theo, instead of results that vanish on the space that completes the word. (simple expands every prefix literally.) A query with no searchable terms (only punctuation), an unterminated quote, or a phrase against a field declared @fulltext(positions: false) is an error. So is .matches on a field without @fulltext; for an unindexed substring test use .contains instead — .contains is literal and never stems, whatever the field's analyzer. While the index of a freshly-declared (or reconfigured) field is still being built for existing objects, .matches on it is an error that reports the progress — see @fulltext.
.matches after a filter or traversal restricts the ranking to those candidates before taking the top k, so you always get up to k results from within the narrowed set.
Limits. A query text may be at most 16 KiB, carry at most 256 terms across all its clauses (a phrase counts each of its words, repeats included), and a phrase at most 32 words; past any of these the query is an error. Under the query governor every posting the search reads and every clause's walk over those postings count against the examined-rows budget (so "x x x" costs three walks of x's postings, not one), and a long postings scan stops at the query's time budget.
Under security rules a search ranks only the documents the caller may read. Each candidate — the documents holding the query's terms, narrowed by any preceding filter or traversal — is checked against the read rule first; the top-k cut, the prefix-expansion cap and the BM25 statistics (document frequency, document count and average length) are then computed over those readable candidates alone, so neither a score, nor the number of rows under k, nor a "prefix matches too many terms" error depends on documents the caller cannot see. Scores therefore differ from the same query run without rules — they are comparable within one result, not across callers. More generally, with rules on every step of a query works only on rows the caller may read: a .filter, .limit, traversal or write after a search or filter never sees an unreadable row (a write over unreadable matches is a no-op, not a permission error). A write straight after Type.get(id) is still judged by the write rule alone, so deleting an object you may delete but not read works when you name it. Paging also changes: a .limit after a filter is no longer pushed into the index scan (it would cut before the read rule), so a filter under rules examines every match and a very large match set can exceed the governor's row budget — narrow it with a more selective indexed filter. One thing rules do not hide: resource limits are charged for the work a query really does, and that includes reading index entries and rows the caller then cannot see, so whether a query is refused for exceeding the examined-rows budget can reflect how many such rows exist — a coarse count, never their contents (the refusal names the configured limit, not how much of it was used).
Ranked results
.similar and .matches produce a ranked result: the same objects as any other query, in rank order, each carrying a score. Over POST /query the score is an extra "score" member on every object; over the binary protocol the result is a Scored frame (or a Reranked frame when a cross-encoder score is present — API Reference); the Rust and TypeScript clients expose it as Row.score (and Row.rerank_score / Row.rerankScore). The score's meaning depends on the step:
| Step | score |
|---|---|
.matches | BM25 relevance — higher is better |
.similar | the index distance under the field's metric (cosine distance, squared L2, or negated dot product) — lower is closer. Always the distance, so it can be thresholded on whatever the deployment's reranking configuration |
A .similar row additionally carries rerank_score — the cross-encoder's relevance, higher is better — when all of these hold: [vectorizer] cross_encoder names a model, the query was a text query (a raw-vector .similar has no text to score against), the reranker model is currently loaded (a load failure is fail-soft — see reranker_error on GET /status), and the row's object has readable source text. Rows come back in rank order either way: the rows the cross-encoder scored first (by rerank_score, descending), then any candidates it could not score (by score, ascending). A .similar step's score is only comparable across queries against the SAME field (the metric is a property of the field).
A .filter, .limit or .offset after a ranked step keeps the order and the scores; a traversal or a mutation drops them.
Mutations — .update, .delete
User.get(1).update({ name: "Alice B.", age: 31 })
Post.get(7).delete()
delete honours the @on_delete policies declared in your schema (remove / cascade / deny).
Guarded writes (compare-and-set)
A write after a filter re-checks that filter on every object, atomically with the write, so a filter on a field's old value works as compare-and-set:
Account.filter(.handle == "h" && .step == 41).update({ step: 42 })
Ledger.filter(.key == "k" && .high_water < 900).update({ high_water: 900 })
Session.filter(.token == "t" && .revoked == false).delete()
The filter selects objects on a snapshot. Each selected object is then written in its own transaction, which re-reads the object and evaluates the filter again on its current committed version:
- If the object is gone, or no longer matches, it is skipped: not written, not returned by
update, and no change event is emitted. - If it still matches, the write commits only if no other transaction has written the object since that read. If one has, the write is retried from a fresh read and a fresh check; the database does this internally, so contention shows up as a skipped object, not as an error.
So any number of concurrent statements guarded on the same old value apply exactly once: one writes the object, and every other one finds it no longer matches. The caller tells which happened from the result: update returns only the objects it wrote (an empty list when it wrote none). delete, link and unlink return no rows, so to learn whether a guarded delete applied, re-read the object (or guard an update instead).
The guarantee covers .update, .delete, .link and .unlink, and the predicates it re-checks are the ones about the written objects themselves: the source filter and every .filter() after the last traversal. .limit, .offset, .similar and .matches in between keep them. A filter before a traversal constrained other objects, which the write does not lock, so it is not re-checked: User.filter(.active == true).posts.delete() deletes the posts of users that were active when the filter ran.
.limit picks the objects before the re-check, not after it. In the queue-claim pattern Job.filter(.status == "queued").limit(1).update({status: "taken"}), a statement that loses the race returns no rows; it does not move on to the next queued job. Retry the statement to claim another.
Writes without a filter behave as before: T.get(id).update(...) writes the object as it is now and fails if it does not exist; T.update(...) (every object) and T.get_many([...]).update(...) skip an object deleted since the read.
The guarantee is per object, not per statement. A statement that writes several objects runs one transaction per object, so another reader can see some of them written and others not yet, and an error part-way (a unique-constraint violation, say) leaves the objects before it written. When several writes must land together, use a transaction.
A write gives up with a write-conflict error only after many consecutive conflicts on the same object (other writers changing it continuously while it still matches); retrying the statement is then safe.
Security rules are checked atomically with the write
Under security rules, the update and delete rules (and the update rule that gates .link / .unlink on the source object) are decided inside each object's write transaction, on the version of the object that write is based on — for point writes (T.get(id).update(...)) as well as filtered ones. Everything the rule reads joins that transaction's conflict check:
- the object's own fields (
resource.ownerUid); - the edges of every relation the rule follows (
resource.editors, including@inversefields) — an edge added, removed or replaced by another writer counts; - the fields of the linked objects it reads (
resource.editors.uid).
If another transaction changes any of these after the write's snapshot, the write is retried from a fresh read and the rule is evaluated again. So a write lands only if the rule allowed it on the state it actually committed over: revoking ownership, removing an editor or adding someone to a deny-list takes effect for every write that commits after the change, with no window in between. A denied object is reported as a permission error and nothing is written for it (no field, index, edge or change event).
The rule is also checked once on the query's snapshot before any object is written, so a statement the rules refuse on any of its objects is normally refused whole. Like the compare-and-set guarantee above, the atomic check is per object: if a rule input changes while a multi-object statement is running, the objects written before the change stay written and the statement stops with a permission error at the first object the rule now refuses.
A create rule sees only the incoming fields (request.*), which no other writer can change, so it has nothing to race.
Links — .link, .unlink
Create or remove a relationship between objects. Edge-field values (if the relationship declares any) go in the optional object literal.
User.get(1).link(User.get(2)) // user 2 becomes a friend of user 1
User.get(1).link(Movie.get(42), { rating: 4.5 }) // with an edge field on favorite_movies
User.get(1).unlink(User.get(2))
The source is whatever the query has reached when .link runs. User.get(1).link(...) links from user 1; a traversal before it moves the source, so User.get(1).friends.link(User.get(2)) links each of user 1's friends to user 2, not user 1. The target is always written as Type.get(id).
The link is made on the source object's relation field to the target's type. When the source type has only one such field, it is found automatically. When it has several (a parent and a related, both pointing to Page), name the field first; the unnamed form is then an error that asks you to:
Page.get(7).link(.parent, Page.get(3))
Page.get(7).link(.related, Page.get(9), { weight: 0.5 })
Page.get(7).unlink(.parent, Page.get(3))
A named field must be a relation field of the source type that points to the target's type.
An @inverse field can't be linked or unlinked directly: it has no edges of its own, and shows the links made through the forward field it names. Link from the forward side instead. With parent: Page and children: [Page] @inverse(Page.parent), to make page 7 a child of page 3:
Page.get(7).link(.parent, Page.get(3)) // page 3's children now include 7
Page.get(3).link(.children, Page.get(7)) // error: link from the other side
An inverse field still counts when the unnamed form looks for a field, so a type with both parent and children must name the field.
Transactions — transaction { ... }
A transaction block is an ordered list of writes that commits as one: every write or none, at one commit version.
transaction {
let $m = Message.create({ subject: "Hello", step: 1 });
MessageContent.create({ body: "…", message: $m });
Message.get($m).link(.labels, Label.get(7), { weight: 0.5 });
Thread.get(9).filter(.rev == 3).update({ rev: 4, last: $m });
Draft.get(12).delete();
}
Each statement is one point write, separated by ;:
| Statement | Writes |
|---|---|
T.create({ ... }), let $name = T.create({ ... }) | a new object; let names it for later statements |
T.get(id).update({ ... }) | the object's fields |
T.get(id).delete() | the object, with its @on_delete policies |
T.get(id).link([.field,] U.get(id) [, { edge fields }]) | an edge, as .link |
T.get(id).unlink([.field,] U.get(id)) | an edge, as .unlink |
Names. A new object's id is not known until the transaction runs, so a create bound with let $name is referred to as $name: in place of an id (Message.get($m), Label.get($m)), or as a field value, which then holds the new object's id (message: $m sets the message relation). A name must be bound once, by a create that comes earlier in the block; anything else (an unknown name, a name used before its create, a name bound twice) refuses the whole block before it runs.
Guards. .filter(...) steps between .get(id) and the write (ANDed together) are the statement's guard: it must hold on the object as the transaction sees it, after the earlier statements' writes, or the whole transaction aborts with a transaction guard rejected error (409 over HTTP). This is compare-and-set across several objects. Without a guard, a statement whose object does not exist aborts the transaction with object not found (404), an unlink included, although a single .unlink statement of a missing source does nothing.
All or nothing. If any statement fails (a @unique value already taken, a missing object, a guard or a security rule that refuses it, a wrongly typed value), nothing is applied. Every statement sees the writes of the statements before it, and a reader outside sees either none of them or all of them. A transaction that conflicts with a concurrent writer is retried internally from a fresh snapshot, like any write.
Change events. Subscribers see one event per changed object, carrying the transaction's commit version and the object's final state: a create followed by an update of the same object in one block is a single create event. A write origin (see the API reference) is stamped on every event of the block.
Security rules. Each statement is checked against its rule as a single write is, inside the transaction, so a rule sees the earlier statements' writes (a link from an object created earlier in the block is judged on that new object). A denial anywhere refuses the whole block with permission denied (403). Each created or updated object comes back as that statement left it, and only if the read rule lets the caller read it in that state; otherwise its result gives the id alone.
Limits. A block holds at most 10,000 statements, and each one counts toward the query governor's row budget. Over the network, the request size limits of POST /query and the binary protocol apply.
Result. One result per statement, in order: the id (and object) of each create and update, and for each unlink whether there was an edge to remove. Over HTTP it is the "transaction" member of the reply; the clients also take the list as data rather than query text (see Write transactions).
Pagination — .offset, .limit
User.filter(.age > 18).limit(10)
User.filter(.age > 18).offset(20).limit(10)
Apply offset before limit. Writing .limit(N).offset(M) is rejected — that order silently drops rows and is treated as a mistake.
Ordering and pages — .order_by, .after
Message.filter(.place == "lobby").order_by(.created, desc).limit(50)
Message.filter(.place == "lobby").order_by(.created, desc).after("AQAAAAAA…").limit(50)
User.order_by(.name)
.order_by(.field) sorts the rows ascending; .order_by(.field, desc) descending. The result is a page: the rows, plus a next_cursor when more rows follow (see the API Reference). Pass that cursor to .after("…") to read the next page. The last page has no cursor.
- Where it goes.
.order_bycomes after the filters, traversals and writes that build the set, and ends the pipeline: only.after(directly after it), then.offsetand.limit, may follow. It cannot follow.similaror.matches, whose rows are ordered by score, and takes one field. The field must be a scalar other thanJson. - Order. Nulls and missing values first ascending, last descending; ties by id in the same direction. The rules are in the schema reference.
- Cursors are opaque strings. A cursor names a position, not a row: rows written or deleted between pages are handled as you would expect. The next page starts right after where the cursor's row was, even if that row is gone; a row inserted before that position is not seen and one inserted after it is. A cursor from a different ordering (type, field or direction) is refused, as is a malformed one, with a
400. A cursor carries its row's value of the ordering field, so ordering by a long string field gives a cursor about as long as that string; order by a short field (a time, a number) when cursors travel in URLs. - Cost. With a type-level
@indexthat matches the query, a page reads aboutoffset + limit + 1entries however large the set is. Without one, the query reads every row of its set, then sorts, as a filter without an index does. Prefer.afterto a growing.offsetfor deep pages: an offset still reads the rows it skips. - Security rules. Every row is checked against the
readrule before it counts, so a page holdslimitreadable rows when that many exist, and the cursor never points into rows the caller cannot read.
Literals
| Kind | Examples |
|---|---|
| String | "hello" |
| Integer | 42, -10 |
| Float | 3.14, -2.5 |
| Bool | true, false |
| Null | null |
| Vector | [1.0, 2.0, 3.0] |
| JSON | { "k": 1, "tags": ["a", "b"] } |
How a literal is interpreted depends on the field's declared type — the
language has no inline type annotations. A string literal becomes a DateTime
when written to a DateTime field, base64-decodes into a Bytes field, and a
raw JSON object/array literal is stored in a Json field:
Event.create({
created: "2026-06-20T12:00:00Z", // DateTime (RFC 3339; or an integer epoch-millis)
blob: "aGVsbG8=", // Bytes (base64)
meta: { "k": 1, "tags": ["a"] } // Json (raw JSON value)
})
These read back faithfully — created as an RFC 3339 string, blob as base64,
meta as inline JSON. A malformed value (a non-RFC-3339 DateTime, invalid
base64, or unparseable JSON) is a clear error, not a silent default.
Examples
// Create
User.create({ name: "Alice", email: "alice@example.com", age: 30 })
// Read by id and by filter
User.get(1)
User.filter(.reputation >= 100 && .active == true).offset(0).limit(20)
// Traverse
User.get(1).friends.posts.filter(.title != "")
// Mutate
User.get(1).update({ reputation: 150 })
Post.get(7).delete()
// Relate
User.get(1).link(.favorite_movies, Movie.get(42), { rating: 5.0 })
// Vector search, narrowed by a filter
Post.filter(.published == true).similar(.embedding, "vector databases", k: 10, rerank: 50)