Add search to your app
Index a model, query it as the person searching, and get facets and highlights that never show a record they may not read.
Status Status is where the work is: Planned (in a milestone, not started), Building (tickets in progress), Preview (usable, may change), then the stability it ships at.
Stability The promise an interface ships with.
- Stable Follows semantic versioning; breaking changes need a new major, 12 months of overlap and a codemod.
- Beta Usable in production; may change before it becomes stable.
- Experimental May change or go away; needs an explicit opt-in in main.yaml.
You will index one model and add a search route. It takes about 15 minutes.
You need
- A MainSDK app with a
dbmodel, hereposts, and anaccessaction that says who may read it.
1. Declare the index
search:
driver: db
indexes:
posts:
model: posts
access: posts.read
fields:
text: { search: true, weight: 2 }
tags: { facet: true, filter: true }The db driver needs no account. Move to typesense or meilisearch later by changing driver and adding the engine's key and regions.
2. Query as the searcher
import { auth, search } from "mainsdk";
export async function GET(req: Request) {
const session = await auth.require(req);
const q = new URL(req.url).searchParams.get("q") ?? "";
return Response.json(await search.query({ index: "posts", q, for: { type: "user", id: session.user }, highlight: true, limit: 10 }));
}for is required, and a query without it fails with MAIN-SEARCH-0003. The tenant and access filters run inside the engine's query, so nothing is filtered after the fact.
3. Keep the index current
Writes to the posts model reach the index through the job outbox, never the request path. To rebuild an index, call search.reindex("posts"); it resumes after a crash. search.status("posts") shows what is pending or failed.
Check that it works
- A post you can read appears in the results; one you cannot read does not.
- Stop the engine: the query fails with
MAIN-SEARCH-0004, and index changes stay queued.
Next
Was this page helpful?