Search
- Introduction
- Configuration
- Making models searchable
- Searching
- Semantic search
- Keeping the index in sync
- Custom engines
- Performance notes
- Troubleshooting search
- Testing
Introduction
dust-framework can add full-text and semantic search to your models. For example, a blog might let readers search posts by title and body while showing only published entries. You mark the fields a search should read on your model, and Post::search("rust") returns the matching posts, ready to filter, order, and paginate like any model query:
use dust::model::model;use dust::search::Searchable;use dust::time::Timestamp;#[model(searchable)]pub struct Post { pub id: i64, #[search] pub title: String, #[search(full_text)] pub body: String, #[search(filterable)] pub published: bool, #[search(filterable, sortable)] pub created_at: Timestamp, pub updated_at: Timestamp,}impl Searchable for Post {}A handler then passes the reader's search terms to Post::search to retrieve the matching posts:
let posts = Post::search(terms) .filter(Post::published.eq(true)) .limit(15) .get() .await?;By default, dust-framework uses the database engine, which runs each search directly against the model's table using LIKE conditions and your database's full-text indexes. Because it requires no extra service and no separate copy of your data, it's a great place to get started.
When your application outgrows database search, such as when readers expect typo tolerance or a table holds millions of rows, you may switch to Meilisearch, Typesense, or Turbopuffer by changing your environment variables. These services keep a dedicated index of your searchable rows, and dust-framework keeps that index in sync when your models change. Your model definitions and search queries stay the same across engines.
Configuration
Search is an optional Cargo feature. Enable search on dust-framework in your application's Cargo.toml:
[dependencies]dust-framework = { version = "1", features = ["database-postgres", "search"] }dust-framework reads your search settings from environment variables. The defaults work for most applications:
| Variable | Default | What it does |
|---|---|---|
SEARCH_ENGINE |
database |
Selects the search engine: database, meilisearch, typesense, turbopuffer, or discard. |
SEARCH_QUEUE |
false |
Runs index syncs from a queued job instead of during the request. |
SEARCH_PREFIX |
No prefix | Prepends text, such as staging_, to every index name and sync lock key so applications that share a search service or cache don't collide. |
Search engines
The database engine searches PostgreSQL, MySQL, MariaDB, and SQLite directly and needs no extra environment variables. When you want to disable indexing and searching, such as on a staging server that shares production's database, set SEARCH_ENGINE=discard. The discard engine stores nothing, finds nothing, and never calls your embedder.
To use a dedicated search service, set SEARCH_ENGINE along with that service's credentials in your .env file.
Choosing an engine
The model definitions and search calls stay the same when you switch engines, but the matching behaviour, the setup, and the failure modes do not:
| Engine | Runs where | Strengths | Limits |
|---|---|---|---|
database |
Your database | No extra service, always current, filters on real columns | No typo tolerance; substring scans; semantic search needs pgvector or MariaDB 11.7+ |
meilisearch |
A Meilisearch server | Typo tolerance, highlighting, engine-side embedders | Writes apply asynchronously; filters need index settings first |
typesense |
A Typesense server | Fast matching, typo tolerance, built-in embedder | Primary keys are text, so no range filters or sorting on them |
turbopuffer |
Turbopuffer's service | Very large namespaces on object storage | Cannot sort a query that has search terms; no similarity cutoff |
discard |
Nowhere | Safe for tests and staging | Finds nothing and never embeds |
Start on database: it needs no deployment step and keeps every result consistent with the row you just wrote. Move to a dedicated engine when readers expect typo tolerance or when the table is large enough that LIKE and full-text scans dominate request time. Because each engine ranks differently, keep the tests that assert on ranking against the engine you run in production, as Testing describes.
Meilisearch
Meilisearch is an open-source search engine that you may self-host or run on Meilisearch Cloud. Set SEARCH_ENGINE, your server URL, and your master or API key:
SEARCH_ENGINE=meilisearch
MEILISEARCH_HOST=http://127.0.0.1:7700
MEILISEARCH_KEY=masterKeyMEILISEARCH_HOST defaults to http://localhost:7700. You may leave MEILISEARCH_KEY unset for a local server started without a master key.
Typesense
Typesense is an open-source search engine that you may self-host or run on Typesense Cloud. Set SEARCH_ENGINE along with your server's host, port, protocol, and API key:
SEARCH_ENGINE=typesense
TYPESENSE_HOST=localhost
TYPESENSE_PORT=8108
TYPESENSE_PROTOCOL=http
TYPESENSE_API_KEY=xyzTYPESENSE_HOST defaults to localhost, TYPESENSE_PORT defaults to 8108, and TYPESENSE_PROTOCOL defaults to http.
Turbopuffer
Turbopuffer is a hosted search engine built on object storage. Set SEARCH_ENGINE, your API key, and your region if it differs from the default gcp-us-central1:
SEARCH_ENGINE=turbopuffer
TURBOPUFFER_API_KEY=your-api-key
TURBOPUFFER_REGION=gcp-us-central1Creating indexes
Dedicated search engines track index settings derived from your field marks, such as which fields are searchable, filterable, and sortable. Run search:index to create missing indexes and push those settings:
dust search:indexWhether you need to run search:index up front depends on the engine:
- Meilisearch requires
search:indexbefore filtering, sorting, or using embedders, because Meilisearch rejects filters and sorts until those settings are pushed. dust-framework waits for the settings update to finish so searches immediately after a deploy use them. - Typesense creates a missing collection automatically on the first write, so you only need
search:indexwhen adding new marked fields to an existing collection. - Turbopuffer creates the namespace and applies your schema automatically on every write, so you can start writing documents immediately without running
search:indexfirst (running it pushes schema changes ahead of the next write). databaseanddiscardkeep no separate indexes, sosearch:indexandsearch:delete-indexreport that there is nothing to do.
Neither Typesense nor Turbopuffer can change the type of an existing field, so after changing a marked field's Rust type, run search:delete-index, search:index, and search:import to rebuild the index. Running search:index again is safe when nothing changed, so you may still include it in your deploy script before search:import.
To create or update a single model's index, pass its struct name or index name (with or without SEARCH_PREFIX, so with staging_, both staging_posts and posts match Post):
dust search:index PostSearching an index that doesn't exist yet returns empty results (and null for raw) rather than failing, so pages keep working before your first import. If searches on a new server find nothing at all, check that SEARCH_PREFIX matches the prefix used when creating the indexes.
To delete an index along with all of its documents and settings, such as after renaming an index with searchable(index = ".."), run search:delete-index with the model's name or the index's name. SEARCH_PREFIX is added automatically unless the name already starts with it:
dust search:delete-index Postdust search:delete-index old_postsWhen the index doesn't exist, the command says there's nothing to delete and still succeeds, on every engine and for any name, so a deploy script that deletes an old index may run again.
Making models searchable
To make a model searchable, add searchable to its #[model(..)] attribute, mark the fields that searches read with #[search], and implement Searchable. Every method on Searchable has a default implementation, so an empty block is enough to start:
// src/models/post.rsuse dust::model::model;use dust::search::Searchable;#[model(searchable)]pub struct Post { pub id: i64, #[search] pub title: String, #[search(filterable)] pub published: bool,}impl Searchable for Post {}Marking fields
A search reads only the fields you mark, so unmarked columns such as stripe_customer_id stay out of your index. A bare #[search] marks a field as searchable text. To rank matches in one text field higher than another (on engines that support field weights), pass weight:
use dust::model::model;use dust::search::Searchable;#[model(searchable)]pub struct Post { pub id: i64, #[search(weight = 3)] pub title: String, #[search] pub body: String,}impl Searchable for Post {}Filtering and ordering also require marks, because a search can only filter or order on fields that the index tracks. Mark a field filterable to make it filterable in search queries, and sortable to make it sortable. A single field may carry both:
#[search(filterable, sortable)]pub created_at: Timestamp,A text field may also be filterable or sortable. Write text beside filterable or sortable when a field should both match search terms and allow filtering, such as a category that readers search by typing or pick from a dropdown:
#[search(text, filterable)]pub category: String,Each field mark controls how the index treats that field:
| Mark | Purpose |
|---|---|
#[search] or #[search(text)] |
Marks the field as searchable text. |
#[search(weight = 3)] |
Ranks matches in this text field higher than lighter fields on engines that support weights. |
#[search(filterable)] |
Makes the field available for search filters. |
#[search(sortable)] |
Makes the field available for ordering search results. |
Text marks apply to String fields, while filterable and sortable apply to any scalar column. The model's primary key is always indexed and can be filtered or ordered without a mark. Primary keys can't be marked for text search; if a query might be an ID, look the row up by primary key in your handler instead.
Engine-specific behavior
While your model definitions and search queries stay the same across engines, each engine has its own strengths and nuances when matching text, indexing fields, and sorting results. Keep the following details in mind when choosing or switching engines.
Database
On the database engine, a bare #[search] runs a case-insensitive substring LIKE match (%terms%) and weight is ignored. For better performance or stricter matching on database queries, you may use two additional text marks:
#[search(prefix)]runs a prefixLIKEmatch (terms%) that can use a standard index, which fits fields such as email addresses or slugs.#[search(full_text)]runs a word-based full-text search ranked by relevance, which fits long text such as bios or article bodies.
use dust::model::model;use dust::search::Searchable;#[model(searchable)]pub struct User { pub id: i64, #[search] pub name: String, #[search(prefix)] pub email: String, #[search(full_text)] pub bio: String,}impl Searchable for User {}Dedicated engines treat prefix and full_text the same as #[search], because they already handle tokenization, prefix matching, and full-text indexing automatically.
A full_text field requires a full-text index on PostgreSQL, MySQL, and MariaDB. Create it in the table's migration with table.full_text:
table.text("body");table.full_text(["body"]);SQLite has no full-text index, so a full_text field there is matched like a bare #[search]: a case-insensitive substring LIKE. No index is required, and prefix still behaves as a prefix match.
Meilisearch and Typesense
Meilisearch and Typesense match whole words and word prefixes with typo tolerance rather than arbitrary substrings, so onara won't match "Editorial Carbonara", while otw matches "Taylor Otwell".
On Typesense, primary keys are stored as text, so searches can't sort by the primary key or filter it with lt, le, gt, or ge (only eq, ne, is_in, and is_not_in).
Turbopuffer
Turbopuffer matches whole words and treats the last word of the search terms as a prefix. Turbopuffer does not support sorting queries that have search terms, so order_by, latest, and oldest fail there unless the search terms are blank.
Naming the index
By default, each searchable model's index is named after its table, with SEARCH_PREFIX in front. On the database engine, the index is the table itself. If you'd like a different index name, such as when two models share one table, pass index to searchable:
#[model(searchable(index = "articles"))]pub struct Post { // ...}Choosing which rows are searchable
By default, every row in the model's table is searchable. When only some rows should appear in search results, such as published posts and never drafts, implement indexed on Searchable. It receives the model's query and narrows it. Every search, sync, and import starts from the query it returns:
use dust::db::Builder;use dust::search::Searchable;impl Searchable for Post { fn indexed(query: Builder<Self>) -> Builder<Self> { query.filter(Post::published.eq(true)) }}Because indexed uses an ordinary model query, it supports any condition, including relationship conditions and eager loading with with. For example, a forum might only make threads with at least one reply searchable. A relationship's exists condition comes from the Relation trait, so import it in the model's file:
use dust::db::Builder;use dust::model::Relation;use dust::search::Searchable;impl Searchable for Post { fn indexed(query: Builder<Self>) -> Builder<Self> { query.filter(Post::comments.exists()) }}Searching
How a search returns models
On a dedicated engine, a search happens in two steps. First dust-framework sends the terms, filters, and ordering to the engine, which returns the primary keys of matching documents in ranked order. Then dust-framework loads those models from your database, preserving the engine's order. On the database engine both steps collapse into one model query.
That design has a few consequences worth knowing:
- The database is the source of truth. The index holds the marked fields and the key, not a second copy of the model. A row deleted from the database cannot come back through a stale index.
- The index can lag the database. Meilisearch applies writes asynchronously, and queued syncs run later; see Keeping the index in sync.
- Filters and ordering are checked against your marks. A filter on an unmarked field fails before the engine is called, instead of returning a wrong result.
keys()skips hydration. When you only need IDs, avoid loading every model and its columns.
Adding searchable to your model's #[model(searchable)] attribute gives the model a search method. Pass the search terms to Post::search and call get to retrieve the matching models, ranked by relevance by default. For example, this handler reads the q query parameter using a #[dust::query] struct and returns the matching posts as JSON:
use dust::prelude::*;use crate::models::Post;#[dust::query]pub struct PostSearch { #[default] q: String,}pub async fn index( Query(search): Query<PostSearch>,) -> dust::Result<Json<Vec<Post>>> { let posts = Post::search(&search.q).get().await?; Ok(Json(posts))}Besides get, you may fetch only the best match, cap the number of results, or retrieve only the matching primary keys without loading the models:
let post = Post::search("rust").first().await?;let posts = Post::search("rust").limit(5).get().await?;let ids = Post::search("rust").keys().await?;first returns Option<Post>, which is None when no row matches.
The full search API mirrors model queries where it can:
| Call | Returns | Notes |
|---|---|---|
get() |
Vec<Model> |
Loads the matching models in rank order |
first() |
Option<Model> |
The best match |
keys() |
Vec<Model::Key> |
Skips loading the models |
limit(n) |
The query | Caps the result count |
filter(condition) |
The query | One field comparison or list membership |
order_by, latest, oldest |
The query | Replaces relevance ranking with a sort |
with(relationship) |
The query | Eager-loads on the returned models |
paginate(n) / simple_paginate(n) |
A paginator | Numbered or previous/next pages |
semantic() |
The query | Ranks by meaning |
hybrid() |
The query | Merges text and meaning rankings |
min_similarity(x) |
The query | Sets the semantic cutoff |
weights(text, semantic) |
The query | Adjusts a hybrid search |
options(json) / raw() |
The query / the engine response | Engine-specific settings and responses |
Post::search returns a dust::search::Query<Post>. If several handlers add the same filters to their searches, such as a public search page and an admin page that both search only published posts, you may write a function that takes and returns that type:
use dust::search::Query;use crate::models::Post;fn published(search: Query<Post>) -> Query<Post> { search.filter(Post::published.eq(true))}Filtering and ordering
A search accepts the same filter conditions as a model query. For example, a blog's search box might restrict results to published posts:
let posts = Post::search(terms) .filter(Post::published.eq(true)) .get() .await?;By default, results are ranked by relevance. If your search page lets users override relevance ranking (for example, sorting matching posts newest first or sorting products by price), call order_by, latest, or oldest:
let posts = Post::search(terms) .filter(Post::published.eq(true)) .latest(Post::created_at) .get() .await?;Some filters apply only when the reader asks for them, such as a category picked from a dropdown beside the search box. Instead of building the search in several steps, pass the optional value to when_some. dust-framework applies the filter only when the value is Some, and passes it the value inside. If Post has a category field marked #[search(filterable)], a handler might filter on the category query parameter only when the request has one:
use dust::prelude::*;use crate::models::Post;#[dust::query]pub struct PostSearch { #[default] q: String, category: Option<String>,}pub async fn index( Query(search): Query<PostSearch>,) -> dust::Result<Json<Vec<Post>>> { let posts = Post::search(&search.q) .when_some(search.category, |query, category| { query.filter(Post::category.eq(category)) }) .get() .await?; Ok(Json(posts))}when does the same for a bool, such as .when(only_published, |search| search.filter(Post::published.eq(true))).
Each filter compares one field with a value, using eq, ne, lt, le, gt, or ge, or with a list of values, using is_in or is_not_in. Every match must pass each filter you add. To match any of several values of one field, such as posts in either of two categories, use is_in:
let posts = Post::search(terms) .filter(Post::published.eq(true)) .filter(Post::category.is_in(["go", "rust"])) .get() .await?;Filters must target a field marked filterable or the model's primary key, and ordering must target a field marked sortable or the primary key.
Blank terms are a special case: on the database engine a text search with empty terms matches every row, while semantic() and hybrid() fail because there is no meaning to compare. A search page usually skips the search entirely when the box is empty and shows a default, date-ordered list instead.
Compound conditions (&, |, !) and SQL-only conditions (like, relationship has, db::raw!) aren't supported on search queries. Put SQL-only constraints in indexed instead.
Loading relationships
When your results need related models, such as each post's author, call with. It eager-loads the relationships onto the returned models as a model query's with does:
let posts = Post::search(terms) .with(Post::author) .get() .await?;To eager-load a relationship on every search of the model, call with inside indexed.
Pagination
To paginate search results, call paginate or simple_paginate. Both return the same paginators as a model query, and their page links keep the request's entire query string, so page 2 of /posts?q=rust links to /posts?q=rust&page=2:
use dust::pagination::Paginator;use dust::prelude::*;use crate::models::Post;#[dust::query]pub struct PostSearch { #[default] q: String,}pub async fn index( Query(search): Query<PostSearch>,) -> dust::Result<Json<Paginator<Post>>> { let posts = Post::search(&search.q) .filter(Post::published.eq(true)) .paginate(15) .await?; Ok(Json(posts))}paginate counts every matching row so it can display the total number of pages. If you only need previous and next links, call simple_paginate to skip the count.
Engine options
Each search service offers settings that dust-framework doesn't wrap, such as Meilisearch's matchingStrategy or Typesense's num_typos. Pass them to options as JSON, and dust-framework merges them into the outgoing request. The database engine sends no request, so a search with options or raw fails there:
use serde_json::json;let posts = Post::search(terms) .options(json!({ "matchingStrategy": "all" })) .get() .await?;When you need more of the engine's response than the loaded models, such as Meilisearch's highlighted snippets, call raw instead of get. It returns the engine's full JSON response as a serde_json::Value. By default, dust-framework asks Meilisearch and Typesense only for each document's primary key, so pass attributesToRetrieve on Meilisearch (or include_fields on Typesense) when you want additional fields in the raw response:
use serde_json::json;let response = Post::search(terms) .options(json!({ "attributesToRetrieve": ["id", "title"], "attributesToHighlight": ["title"], })) .raw() .await?;if let Some(hits) = response["hits"].as_array() { for hit in hits { let id = hit["id"].as_i64(); let highlighted = hit["_formatted"]["title"].as_str(); // ... }}Any option with the same name as a parameter dust-framework sends replaces dust-framework's value. For example, passing Meilisearch's filter replaces dust-framework's generated filters, and passing limit overrides dust-framework's pagination size.
Passing a native filter option is also how you express OR conditions across different fields. Because it replaces every filter dust-framework builds (including tenant filters such as team_id), include all required conditions in the expression. For example, on Meilisearch, with team_id, shared, and user_id marked filterable:
let filter = format!( "team_id = {} AND (shared = true OR user_id = {})", user.team_id, user.id);let posts = Post::search(terms) .options(json!({ "filter": filter })) .get() .await?;Semantic search
A text search finds posts that contain the reader's words, but readers often describe what they want in different words. Someone typing "pasta recipes" wants your post titled "How I make carbonara" even though it never uses the word "pasta".
Semantic search matches posts by meaning. An embedding model converts each post's text into an embedding, a list of numbers that places texts with similar meanings close together, and each search compares the reader's terms against the stored embeddings.
Embedding your models
To make a model searchable by meaning, declare its embeddings in #[model(..)] with the number of dimensions your embedding model produces, such as 1,536 for OpenAI's text-embedding-3-small:
use dust::model::model;use dust::search::Searchable;#[model(searchable(embedding(dimensions = 1536)))]pub struct Post { pub id: i64, #[search(weight = 3)] pub title: String, #[search(full_text)] pub body: String,}impl Searchable for Post {}How dust-framework stores those vectors depends on your search engine:
- Meilisearch, Typesense, and Turbopuffer store each model's embedding directly in the search index alongside its other fields, so your database table needs no
embeddingcolumn. After addingembedding(...), runsearch:index(on Meilisearch and Typesense) so the index includes the vector field, then runsearch:importto embed existing rows. databasestores each model's embedding in a vector column namedembeddingon the model's table (supported on PostgreSQL with pgvector and MariaDB 11.7+).
Storing embeddings in your database
If you're using the database engine, add a nullable embedding vector column with the same number of dimensions in a migration. Your model struct doesn't need a field for it:
table.vector("embedding", 1536).nullable();On PostgreSQL, you may chain .index() to add an HNSW vector index for faster semantic searches on large tables. To learn more, check out the schema builder guide's section on vector columns:
table.vector("embedding", 1536).nullable().index();Registering an embedder
dust-framework doesn't call an embedding provider itself, so register an embedder function with app.search().embed_with in src/app.rs. Your embedder receives a Vec<String> and returns one dust::db::Vector per input text in the same order:
// src/app.rsuse dust::db::Vector;Application::configure() .with_services(|app| { app.search().embed_with(|texts: Vec<String>| async move { // Generate embeddings with OpenAI or another provider... Ok(Vec::<Vector>::new()) }); }) // ...Once registered, dust-framework embeds a model whenever it syncs (up to 100 rows per call). On the database engine, dust-framework still embeds models after create! and after updates to marked fields, saving the vector to the embedding column without triggering another sync. To embed rows that already exist, run search:import.
Customizing the embedded text
By default, dust-framework embeds all non-empty text fields marked for search (#[search], prefix, full_text, or weight), joined with blank lines. Unmarked columns are never embedded or sent to the index.
To customize the text that gets embedded (for example, embedding only the title when bodies exceed your model's token limit), implement embedding_input. Because dust-framework can't tell which columns embedding_input reads, returning Some syncs on every update unless you also override needs_reindex:
use dust::search::Searchable;impl Searchable for Post { fn embedding_input(&self) -> Option<String> { Some(self.title.clone()) }}When the text to embed is blank, dust-framework skips calling your embedder and clears the model's stored embedding.
Searching by meaning
Call semantic to rank posts by how close their stored embedding is to the embedding of the reader's terms, most similar first. dust-framework embeds the terms when the search runs and doesn't match the post's text directly, so "pasta recipes" finds the carbonara post:
let posts = Post::search("pasta recipes") .semantic() .limit(10) .get() .await?;Closeness is measured by cosine similarity, where 1 represents identical meaning and values fall toward 0 for unrelated text. On the database engine, a semantic search keeps posts whose similarity is at least 0.4 by default. Meilisearch, Typesense, and Turbopuffer rank every post by similarity, with no cutoff. Pass min_similarity to set the cutoff yourself:
let posts = Post::search(terms) .semantic() .min_similarity(0.5) .paginate(15) .await?;On Meilisearch, min_similarity is a threshold on Meilisearch's ranking score rather than on cosine similarity, and a post with an unrelated meaning scores about 0.5 there. Turbopuffer has no similarity cutoff, so min_similarity fails there.
Because each embedding model distributes cosine similarity scores differently, you may need to tune min_similarity against your own data by testing a few sample queries and raising the threshold where irrelevant results begin.
Filters, with, limit, and pagination work as they do in a text search. Because similarity determines the order, a semantic search with order_by, latest, or oldest fails with an error naming the conflict. A semantic or hybrid search with blank terms also fails, because there is no meaning to compare, so fall back to text search when the search box is empty.
Hybrid search
A semantic search can miss a post that contains an exact keyword or product code, while a text search misses posts that express the same idea in different words. Calling hybrid combines both, merging the text ranking and the semantic ranking so posts that score well in both appear first:
let posts = Post::search(terms).hybrid().paginate(15).await?;Text and semantic rankings carry equal weight by default (1.0 and 1.0). To emphasize one over the other, call weights with the text weight followed by the semantic weight. The numbers are relative: passing 1.0 and 2.0 gives semantic meaning twice as much influence as text matching, which works well in a help center where readers rarely guess your exact terminology:
let posts = Post::search(terms) .hybrid() .weights(1.0, 2.0) .paginate(15) .await?;min_similarity sets the minimum similarity for the semantic half of a hybrid search, so a post that matches neither the reader's words nor their meaning never appears.
Each engine merges the two rankings its own way, so the same search may order posts differently on each.
Letting the engine embed
If you prefer not to call an embedding provider from your application, Meilisearch, Typesense, and Turbopuffer can generate embeddings for your documents and search terms themselves. Your model only needs the standard #[model(searchable)] attribute and text marks, with no embedding(...) declaration and no embed_with callback:
use dust::model::model;use dust::search::Searchable;#[model(searchable)]pub struct Post { pub id: i64, #[search(weight = 3)] pub title: String, #[search] pub body: String,}impl Searchable for Post {}Once you configure the embedding environment variable for your chosen engine using one of the examples below, semantic() and hybrid() will work automatically.
Typesense
Set TYPESENSE_EMBEDDING_MODEL to a model Typesense supports, such as its built-in ts/all-MiniLM-L12-v2, then run dust search:index. The command adds an embedding field that Typesense computes from your model's text fields:
TYPESENSE_EMBEDDING_MODEL=ts/all-MiniLM-L12-v2Turbopuffer
Set TURBOPUFFER_EMBEDDING_MODEL to one of Turbopuffer's embedding models available in your region. dust-framework writes each post's text fields, joined with blank lines, to an embedding_input attribute that Turbopuffer embeds:
TURBOPUFFER_EMBEDDING_MODEL=openai/text-embedding-3-smallBecause Turbopuffer bills per embedded token, run dust search:import once to embed existing rows rather than on every deploy. If the namespace already holds documents from before you set TURBOPUFFER_EMBEDDING_MODEL, rebuild the namespace with search:delete-index, search:index, and search:import.
Meilisearch
Set MEILISEARCH_EMBEDDING_SOURCE to huggingFace for a model that Meilisearch runs itself, or to openAi, and name the model in MEILISEARCH_EMBEDDING_MODEL. An OpenAI model also requires MEILISEARCH_EMBEDDING_API_KEY:
MEILISEARCH_EMBEDDING_SOURCE=huggingFace
MEILISEARCH_EMBEDDING_MODEL=BAAI/bge-small-en-v1.5MEILISEARCH_EMBEDDING_SOURCE=openAi
MEILISEARCH_EMBEDDING_MODEL=text-embedding-3-small
MEILISEARCH_EMBEDDING_API_KEY=sk-...Because Meilisearch stores embedder configuration in each index's settings, run dust search:index (even on a new application with no data yet) to register the embedder on your searchable indexes. Meilisearch embeds the first 400 bytes of each model's marked text fields, joined with blank lines.
If you later change the source, model, or marked text fields (or unset MEILISEARCH_EMBEDDING_SOURCE), run dust search:index again to update or remove the embedder.
If you'd rather configure an embedder in each index's settings yourself (such as one with a custom documentTemplate, as Meilisearch's AI-powered search guide describes), set MEILISEARCH_EMBEDDER to its name instead. dust-framework then searches with that embedder without modifying its settings:
MEILISEARCH_EMBEDDER=postsKeeping the index in sync
Whenever your application calls create!, update!, delete, or destroy on a searchable model, dust-framework syncs the row after the write's database transaction commits. If a transaction rolls back, nothing syncs.
Typesense and Turbopuffer reflect a synced write as soon as it returns. Meilisearch applies writes asynchronously in the background, so a new or updated post may take a moment to appear in search results after the write completes.
Each sync re-reads the row through indexed. If indexed still returns the row, dust-framework sends its marked fields to the index. If it doesn't, such as when a post is unpublished or deleted, dust-framework removes the row from the index.
An update syncs only when it changes a marked field or the primary key, so updating an unmarked column such as a view count skips syncing. A model that defines indexed or embedding_input syncs on every update because dust-framework can't tell which columns those methods inspect. To control which column changes trigger a sync instead, override needs_reindex:
use dust::model::Changes;use dust::search::Searchable;impl Searchable for Post { fn needs_reindex(&self, changes: &Changes<Self>) -> bool { changes.has(Post::title) || changes.has(Post::author_id) }}If the search engine fails during a sync, such as when the search service is unreachable, the database write still succeeds because the row is already saved. Instead of failing the write, dust-framework reports the sync error with the model name and key, and create!, update!, delete, or the surrounding transaction returns as usual. For automatic retries during brief outages, enable queued syncs. Once the service recovers, pass the affected rows to search::sync or run search:import to resync the table. Because you call search::sync directly, it returns sync errors to the caller.
The database engine queries the table directly and has no separate index to sync, except for the embeddings of a model that declares them.
Queueing syncs
By default, dust-framework syncs the index before the model write returns. In production, set SEARCH_QUEUE=true so syncs run on your queue and a slow search service never delays web requests:
SEARCH_QUEUE=trueWhen an editor saves a post several times in a minute, the index only needs the final version. dust-framework debounces single-row syncs so the job waits 5 seconds for further edits (up to 1 minute maximum) before running. If the search service is temporarily unavailable, queued syncs retry up to 10 times with a 1, 5, and 30 second backoff before moving to the failed jobs table with an error naming the model and keys (such as syncing `Post` 42: ...).
Each single-row sync also acquires a lock on that row in your default cache store so an older, slower sync can't overwrite a newer one. If a queued sync finds the row locked, it releases back onto the queue for a second, which counts as one of its 10 tries. Because both debouncing and row locks live in your cache, use a shared cache store such as database or redis in production.
To adjust the debounce windows, create a src/config/search.rs configuration file and register it in src/config/mod.rs:
// src/config/search.rsuse dust::config::search::Search;use dust::config::{self, Env};use dust::time::ToSpan;#[config::section]fn search(env: &Env) -> Search { Search { debounce_for: 10.seconds().into(), max_wait: 2.minutes().into(), ..Search::from_env(env) }}Writes that skip model events
Bulk query operations such as Post::query().filter(..).update(), insert, and upsert don't dispatch model events, so dust-framework doesn't sync them automatically. After running a bulk write, pass the same query to search::sync:
use dust::search;Post::query() .filter(Post::author_id.eq(author.id)) .update() .published(false) .await?;search::sync(Post::query().filter(Post::author_id.eq(author.id))).await?;search::sync accepts a model query, a single model such as &post, or a list of models. It extracts their primary keys, re-queries the database through indexed in chunks of 500, upserts the rows that still match, and removes any keys that no longer exist or no longer match indexed. When SEARCH_QUEUE=true, it dispatches one queued job per 500 rows without debouncing.
When you already have the IDs of records to remove, Post::destroy(ids).await? deletes them and syncs the index automatically. For a query-based bulk delete, search::sync can't see rows that were already deleted, so load the posts first, run the delete, and pass them to search::sync to remove them from the index:
use dust::search;let posts = Post::query().filter(Post::author_id.eq(author.id));let deleted = posts.get().await?;posts.delete().await?;search::sync(&deleted).await?;Pausing syncing
When you need to write many rows without syncing each one individually, such as inside a seeder that imports the whole table afterward, wrap the writes in search::without_syncing:
use dust::search;search::without_syncing(async || { // Create the posts... Ok(())}).await?;Other model event listeners continue to run inside without_syncing. Calling search::sync explicitly inside the closure still syncs the rows you pass to it. Writes performed inside a database transaction do not sync even after the transaction commits, whether without_syncing wraps the transaction or runs inside it.
After a seeder that pauses syncing, or one that inserts rows with a bulk insert, run search:import so the index holds the new posts:
dust db:seeddust search:import PostImporting and flushing
When you make an existing model searchable or change its marks, run search:import to upsert every row returned by indexed in chunks of 500, updating existing documents in place. When SEARCH_QUEUE=true, dust-framework queues one job per 500 rows instead. Pass the model's struct name or index name (with or without SEARCH_PREFIX):
dust search:import PostTo clear the index before importing (for example, to remove stale documents that no longer match indexed), pass --fresh. To remove every document from a model's index without re-importing, run search:flush:
dust search:import Post --freshdust search:flush PostFor a model that declares embeddings, search:import also regenerates embeddings for every row (including on the database engine, where it populates the embedding column). Run it after switching embedding models or changing the text a model embeds. Because dust-framework calls your embedding provider in batches of 100 rows, importing a large table may take a while.
Custom engines
If you want to use a search service that dust-framework doesn't ship with, such as Algolia, implement search::Engine for your own type. An engine stores the documents dust-framework sends and answers searches with the keys of matching rows. dust-framework validates filters and orders against your marks before calling the engine, then loads the models for the returned keys:
use dust::search::{Document, Engine, Hits, Index, Search};use serde_json::Value;pub struct Algolia { pub app_id: String,}impl Engine for Algolia { async fn upsert( &self, index: &Index, documents: &[Document], ) -> dust::Result<()> { // Send the documents to Algolia... todo!() } async fn delete(&self, index: &Index, keys: &[Value]) -> dust::Result<()> { // Remove the documents with these keys... todo!() } async fn search(&self, index: &Index, search: &Search) -> dust::Result<Hits> { // Search Algolia and return the keys it finds... todo!() } async fn flush(&self, index: &Index) -> dust::Result<()> { // Remove every document... todo!() } async fn sync_index(&self, index: &Index) -> dust::Result<()> { // Create the index when it's missing, and send its settings... todo!() } async fn delete_index(&self, name: &str) -> dust::Result<bool> { // Delete the index, returning whether it existed... todo!() }}Next, select the engine in src/config/search.rs using EngineConfig::custom and attach your settings struct:
// src/config/search.rsuse dust::config::search::{EngineConfig, Search};use dust::config::{self, Env};#[derive(Debug)]pub struct AlgoliaSettings { pub app_id: String,}#[config::section]fn search(env: &Env) -> Search { let settings = AlgoliaSettings { app_id: env.get("ALGOLIA_APP_ID").unwrap_or_default(), }; Search { engine: EngineConfig::custom("algolia").settings(settings).into(), ..Search::from_env(env) }}Finally, register the engine factory under the same name in src/app.rs. dust-framework invokes the factory on the first search or sync and passes your settings through definition.settings:
// src/app.rsApplication::configure() .with_services(|app| { app.search().extend("algolia", async |_app, definition| { let settings = definition.settings::<AlgoliaSettings>()?; Ok(Algolia { app_id: settings.app_id.clone(), }) }); })A package may register a custom engine inside its service provider's register method instead. If SEARCH_ENGINE names an engine that no code registered, the application fails to start with an error naming it.
Performance notes
- Mark only what you search. An unmarked column is never sent to the index, which keeps documents small and avoids leaking fields such as billing identifiers.
- Narrow the index with
indexed. Indexing only published rows makes every search smaller and keeps drafts from competing for relevance. - Sync less often with
needs_reindex. A model that definesindexedorembedding_inputotherwise syncs on every update, even when no searched field changed. - Queue syncs in production.
SEARCH_QUEUE=truemoves syncing off the request path and debounces repeated edits to the same row. - Import in batches, not one row at a time.
search:importwalks the table in chunks of 500; an embedding model is called in batches of 100. - Use
keys()when you only need IDs, such as feeding a background job or a second query, instead of hydrating every model. - Prefer
prefixfor slugs and addresses, andfull_textfor prose. A bare#[search]substring scan on a large text column is the slowest option on thedatabaseengine. - Count only when the UI needs a total.
paginatecounts every matching row;simple_paginateskips that query. - Keep the cache shared. Queued syncs use the cache for debouncing and row locks, so a per-process cache cannot coordinate workers.
- Avoid
raw()for normal reads. It asks the engine for a response shaped for your own parsing;get()already loads the models.
Troubleshooting search
| Symptom | Likely cause | What to do |
|---|---|---|
| A newly deployed index returns nothing | No documents imported yet | Run search:index and search:import |
| A new server finds nothing while development works | SEARCH_PREFIX differs from the one used to build the index |
Use the same prefix, or rebuild the index |
| A filter is rejected | The field is not marked filterable |
Add the mark and re-import |
| An ordering is rejected | The field is not marked sortable |
Add the mark and re-import |
the database engine can't filter ... by ... |
The field belongs to a search document, not a table column | Use a column, or switch to an engine with an index |
options or raw fails on the database engine |
That engine sends no request | Use a dedicated engine for engine-specific options |
| A row is missing right after a write | Meilisearch applies writes asynchronously, or the sync is queued | Wait, or run search:import |
| A deleted row still appears | A bulk delete skipped model events | Sync the loaded models, or import with --fresh |
| A semantic search fails with blank terms | There is no meaning to embed | Fall back to a date-ordered list |
A semantic search rejects order_by |
Similarity defines the order | Remove the explicit ordering, or use a text search |
| Turbopuffer rejects an ordering | It cannot sort a query that has terms | Drop the ordering or clear the terms |
| Typesense rejects a primary-key range filter | Typesense stores keys as text | Use eq, ne, is_in, or is_not_in |
A MySQL or MariaDB full_text test finds nothing |
The test's transaction is uncommitted | Test full-text search on PostgreSQL |
| Every test calls your embedding provider | The model declares embeddings | Switch tests to SEARCH_ENGINE=discard |
When a search service is unreachable, the model write still succeeds: dust-framework reports the sync error instead of failing the request. After the service recovers, pass the affected rows to search::sync or run search:import.
Testing
Most tests of searchable models should run on the database engine. New applications pin SEARCH_ENGINE=database in src/testing.rs, so your tests use it even when your .env selects Meilisearch for development. The database engine searches your test database directly, so a test that creates a post and searches for it needs no search service and no setup beyond your usual test database:
use dust::model::create;use dust::testing::prelude::*;#[dust::test]async fn the_search_page_finds_published_posts( app: Application,) -> dust::Result<()> { create!(Post { title: "Rust tips", published: true }).await?; create!(Post { title: "Rust drafts", published: false }).await?; app.get("/posts?q=rust") .await .assert_ok() .assert_json(json!({ "data": [{ "title": "Rust tips" }] })); Ok(())}A model that declares its embeddings calls your embedder each time it syncs, even on the database engine, so these tests would call your embedding provider. When a test doesn't care about search, such as a test of a post's edit form, run it on the discard engine instead. The discard engine indexes nothing, finds nothing, and never calls your embedder. To use it for every test, change the SEARCH_ENGINE override in src/testing.rs:
// src/testing.rs.with_envs([ // ... ("SEARCH_ENGINE", "discard"),])Testing against a dedicated engine
Engine-specific behavior, such as Typesense's typo tolerance, only shows up against the real service. Keep those tests in a separate file such as tests/search_engines.rs and mark them #[ignore]. Override SEARCH_ENGINE with with_envs and set a dedicated SEARCH_PREFIX (such as test_blog_) so deleting the test index never touches your development indexes:
// tests/search_engines.rsuse dust::model::create;use dust::testing::prelude::*;fn app_on_typesense() -> Application { app::testing::configure() .with_envs([ ("SEARCH_ENGINE", "typesense"), ("SEARCH_PREFIX", "test_blog_"), ]) .create()}#[dust::test(app = app_on_typesense)]#[ignore = "needs Typesense"]async fn typesense_tolerates_typos(app: Application) -> dust::Result<()> { app.command("search:index Post").await.assert_successful(); let post = create!(Post { title: "Carbonara at home" }).await?; let found = Post::search("carbonra").keys().await; app.command("search:delete-index Post").await.assert_successful(); assert_eq!(found?, [post.id]); Ok(())}To run only this group, pass --ignored, and add --test search_engines to run only the tests in that file:
cargo test -- --ignoredcargo test --test search_engines -- --ignored[!NOTE] On MySQL and MariaDB, a full-text search can't see rows written inside an uncommitted transaction. Because tests using
refresh_databaseroll back without committing, a test on MySQL or MariaDB doesn't findfull_textmatches. Test them on PostgreSQL.