Query
Filter records with structured query documents: nested fields, and/or/not, pagination, and an explain option that shows whether a filter uses an index.
Overview
Query lets you ask the workspace: "give me every record where X", with X expressed as a structured filter document. The filter runs on the workspace, so only the matches are sent to you. Use it for any query that touches more than one thread, any filter over body shape (body.kind, body.priority, body._refs.*), or any data large enough that filtering in your own code would waste bandwidth.
Two entry points:
- HTTP:
POST /v1/records/querywith a JSON body describing the filter. - SDK:
client.richQuery({ filter, ... })(TypeScript) orawait client.query(filter, ...)(Python).
This guide covers both, the filter format, and how to use the explain flag to check that an index is being used.
Quick Start
# All INTEND records on task threads from the dev agent, newest first.
curl -s -X POST http://localhost:9100/v1/records/query \
-H 'content-type: application/json' \
-d '{
"filter": {
"act": "INTEND",
"actor": "did:sync:agent:dev",
"body.kind": { "$in": ["core.task.record", "core.task.record.v1"] }
},
"sort": { "clock": -1 },
"limit": 20
}'The same query from TypeScript:
import { Client, Identity } from "@syncropel/sdk";
const client = new Client({
endpoint: "http://localhost:9100",
identity: Identity.static("did:sync:user:alice"),
});
const result = await client.richQuery({
filter: {
act: "INTEND",
actor: "did:sync:agent:dev",
"body.kind": { $in: ["core.task.record", "core.task.record.v1"] },
},
sort: { clock: -1 },
limit: 20,
});
for (const rec of result.records) {
console.log(rec.id, rec.body);
}And Python:
from syncropel import Client, Identity
client = Client(
endpoint="http://localhost:9100",
identity=Identity.static("did:sync:user:alice"),
)
records = await client.query(
filter={
"act": "INTEND",
"actor": "did:sync:agent:dev",
"body.kind": {"$in": ["core.task.record", "core.task.record.v1"]},
},
sort={"clock": -1},
limit=20,
)
for rec in records:
print(rec["id"], rec["body"])Filter Grammar
A filter is a JSON object. Top-level keys are AND-combined. Each value is either a plain value (shorthand for $eq) or an operator object.
Comparison operators
| Operator | Semantics | Example |
|---|---|---|
$eq | field equals value | { "act": { "$eq": "KNOW" } } |
$ne | field differs from value | { "body.status": { "$ne": "cancelled" } } |
$gt | greater than | { "clock": { "$gt": 100 } } |
$gte | greater than or equal | { "clock": { "$gte": 100 } } |
$lt | less than | { "clock": { "$lt": 1000 } } |
$lte | less than or equal | { "clock": { "$lte": 1000 } } |
$in | field in list | { "actor": { "$in": ["did:...", "did:..."] } } |
$nin | field not in list | { "act": { "$nin": ["DO", "CALL"] } } |
$like | SQL LIKE pattern | { "body.title": { "$like": "music/%" } } |
$ilike | case-insensitive LIKE | { "body.title": { "$ilike": "%LOVE%" } } |
$exists | field present (true) or absent (false) | { "body.awaits": { "$exists": true } } |
A plain value, such as { "act": "KNOW" }, is equivalent to { "act": { "$eq": "KNOW" } }.
Logical combinators
| Operator | Semantics | Example |
|---|---|---|
$and | all children must match | { "$and": [{ "act": "KNOW" }, { "clock": { "$gt": 0 } }] } |
$or | any child matches | { "$or": [{ "act": "DO" }, { "act": "CALL" }] } |
$not | child must not match | { "$not": { "actor": "did:sync:system:engine" } } |
Top-level fields are AND-combined implicitly, so $and is usually only needed inside $or/$not.
Allowed field paths
Only these paths are allowed. Other fields, such as signatures, can't be queried.
- Top-level columns:
id,thread,actor,act,clock,data_type,namespace,created_at - Body paths:
body.<segment>[.<segment>...]where each segment matches[A-Za-z0-9_-]+
So body.kind, body.priority, and body._refs.music_artist all work; body alone (without a sub-path) is rejected.
Request Shape
{
"filter": { /* the filter described above */ },
"thread": "th_optional_scope",
"sort": { "clock": -1 },
"limit": 100,
"offset": 0,
"explain": false
}thread: optional. Limits the query to one thread, the same as adding{ "thread": "th_..." }to the filter. This is fast.sort: an object with one key; the value is1for ascending,-1for descending. Example:{ "clock": -1 }(newest first),{ "created_at": 1 }(oldest first),{ "body.priority": -1 }(highest priority first, but see body-kind manifests for why you'll want to declare body fields first).limit: default 100, clamped to 1000. Asking for more returns 1000 rows andcapped: true; readcappedto know a page is partial.matched_totalcounts only the rows you are allowed to see, so it can be lower than the workspace's real total. Usecapped, notmatched_total, to decide whether you have the whole answer.offset: for pagination. Once you have a last-seen clock, prefer{ "clock": { "$gt": last_clock } }as a cursor: it is cheaper than a deep offset.- Counts and pages: a count that takes more than 250 ms answers
read.total: nullwithread.total_at_least; send"total": "skip"to count nothing. Sendnext_cursorback unchanged ascursor, or you get400 CURSOR_INVALID. A read that takes too long answers503 READ_BUDGET_EXCEEDED. See Reads, budgets and cursors. - Who can filter on what: callers other than the owner can filter, sort or group only on the routing fields (
body.kindand the record's own fields) and on the columns of views declared for them; any other body field returns400 QUERY_FIELD_NOT_READABLE {field}."own_writes": trueserves the caller's own writes with body filters. See the rules. explain: whentrue, the response includes aplandescribing which fields used an index and which fields had to scan record bodies.
The same grammar, from inside an actor
An actor working on a task uses this same filter format through its query_thread
tool instead of HTTP, with the same access rules:
{"thread": "th_library", "filter": {"body.kind": "track.v1", "body.labeled": false}, "count_only": true}count_only returns how many records match without returning them, so an
actor can count a large thread without loading it all. A sandboxed run sees
exactly what its credential could read anyway.
Two messages are worth knowing. A field path that can't be used is named in the error (unknown field path: kind; body fields are body.<path>). And "the filter matched nothing" is reported differently from "the thread may hold records outside this run's view". Neither proves nothing exists, so don't treat them as the same answer.
Using explain
The explain flag is how you verify a query is using an index before running it against a large set of records:
curl -s -X POST http://localhost:9100/v1/records/query \
-H 'content-type: application/json' \
-d '{
"filter": { "thread": "th_abc...", "body.kind": "music.catalog.track" },
"limit": 1,
"explain": true
}' | jq '.plan'Example response:
{
"indexed_fields": ["thread"],
"unindexed_fields": ["body.kind"]
}The plan says body.kind was matched by scanning record bodies, a slow scan. To make it use an index, declare a body-kind manifest:
spl config add-body-kind-manifest \
--kind music.catalog.track \
--indexed-field body.kind \
--indexed-field body.titleAfter the workspace reloads config, queries on body.kind are served from the new index. The plan's unindexed_fields list still names body.kind, because it lists every body.* path whether or not an index is used; measure the query time to confirm.
Patterns
"Most recent by thread"
{
"thread": "th_abc...",
"sort": { "clock": -1 },
"limit": 50
}The thread shortcut is fast however much data you have.
"All tasks assigned to a specific agent"
{
"filter": {
"body.kind": { "$in": ["core.task.record", "core.task.record.v1"] },
"body.assigned_to": "did:sync:agent:dev"
},
"sort": { "clock": -1 }
}Declare body.kind + body.assigned_to in a manifest to avoid the body scan once your task log exceeds a few thousand records.
"Records produced in the last hour"
{
"filter": {
"created_at": { "$gte": 1719830400 }
},
"sort": { "created_at": -1 },
"limit": 100
}created_at is already indexed; no manifest needed.
"Reference lookup"
{
"filter": {
"body._refs.music_artist": "spotify:artist:4Z8W4fKeB5YxbusRsdQVPb"
}
}References stored via Ref.* constructors in the SDK live at body._refs.<entity>. Declare each reference path you query in a manifest for speed.
"Pending decision-gate proposals"
{
"filter": {
"act": "KNOW",
"body.awaits": "actor_decision"
},
"sort": { "clock": -1 }
}Limits & Failure Modes
- Filter depth: nested
$and/$orworks, but deep nesting gets slower. Keep filters under about 10 levels. - Type mismatches: comparing a body field that is sometimes a string and sometimes an object returns no match; the comparison uses the stored type, so a text filter won't match when the stored value is an object. Use
$exists: trueif you only need to check presence. - No joins: the filter operates on one record at a time. For "records where another record referencing them exists", compose two queries client-side.
- SDKs on network errors: both SDKs return an empty record list (not an exception) on network or server errors. An empty list can mean "no matches" or "the request failed". Use the
onEmithook or the raw HTTP call if you need to tell them apart.
A query can be a record (core.query.v1)
Everything above is a filter you send and a result you read. When a query is worth keeping (a view you return to, a named scope, a standing question), you save it as a record of kind core.query.v1.
A one-off filter, a saved View and a standing (live) query are all the same kind of record, core.query.v1, kept on the th_queries thread. The record carries:
pipeline: the filter, facets, sort and window (the same filter you would send directly).name: required once the query issaved.saved/live: lifecycle flags.savedturns a one-time filter into a lasting View;livemakes it a standing query.provenance: where it came from, assource_thread(the conversation that shaped it),trigger_record,derived_from(an earlier query it was copied from).
A saved View has a lasting identity and history you can revisit and share, so you don't have to retype it. Queries are saved and promoted in the workspace (the Studio scope bar). There is no CLI command for them: you write a core.query.v1 record like any other.
core.query.v1 is distinct from core.graph.query.v1 (a request to explore a connected workspace's graph). The two are different and not interchangeable.
Next Steps
- Body-Kind Manifests: declare which body fields to index so filters on those fields run fast.
- CEL Expressions: when you need conditions for triggers, routing or preconditions, use CEL.
- TypeScript SDK, Python SDK: full client reference.