Skip to Content
GuidesSetting Up AI Search

Setting Up AI Search

This guide walks you through enabling semantic search for a project. By the end you will have a search endpoint that understands natural language, respects who is asking, and keeps itself up to date.

For the reference version of everything here, see AI & Search.

Prerequisites

  • A Foir project with content
  • An API key with search:read for cross-model search, or search:read:<model> for a single model

What you will build

A search experience that finds content by meaning rather than keywords, ranks by similarity, and returns only what the caller is entitled to see in the locale and variant they would actually be served.

Step 1: Turn embeddings on for a model

  1. Go to Content > Models
  2. Select the model
  3. Switch on Embeddings in its settings and save

That starts maintaining embeddings for records written from now on.

It does not embed the records you already have. Backfilling is the expensive part, so it is a separate, priced step rather than a side effect of the switch. If your model is empty or nearly so, you can skip straight to step 3. If it already holds content, do step 2 first.

Choose which fields are embedded

While you are in the schema builder, check the Embedded for semantic search switch on each prose field. It appears on text and prose fields once the model capability is on, and defaults to on.

The one change worth making by hand: switch it off for text fields that hold identifiers. A slug is a text field by type, so it embeds by default, and an identifier in the embedding is noise that costs money and blunts ranking.

Non-prose types are never embedded and offer no switch, so there is nothing to do for them.

Step 2: Price and run the backfill

Only needed when the model already has content.

Estimate first. In the console, open the model’s Embeddings tab in Content > Models and click Estimate backfill. Over MCP that is foir_manage_embeddings with action backfill_estimate, or call EstimateEmbeddingBackfill on the platform API. You can run the estimate while the capability is still off, which is the point of it.

The estimate reports:

FieldMeaning
record_countRecords the backfill covers
already_embedded_recordsRecords that already hold an embedding; unchanged content re-embeds free
estimated_tokensApproximate embedding tokens
estimated_credits_microApproximate AI-credit cost of the whole backfill, in millionths of a credit (1,000,000 is one credit)

It errs high, so real spend usually comes in under it.

When you are happy with the number, click Start backfill and confirm (or run backfill_start, or StartEmbeddingBackfill). It queues the work and spends real AI credits.

Watch progress on the model’s Embeddings tab in Content > Models, which shows embedded against total, coverage and pending.

Step 3: Let it keep itself current

There is nothing to wire up. After a record write commits, embedding runs in the background with a short delay, and rapid edits collapse into a single job. A record is normally searchable within about half a minute of you finishing with it.

Two behaviours to expect:

  • On a publishing or versioning model, only published content is embedded. A draft is not searchable, and a record that has never been published cannot match. This is the most common reason a record seems missing from results.
  • Unchanged content costs nothing. Re-saving without editing skips the work.

A reconciliation sweep runs behind all of this, so a record whose job was lost gets picked up rather than staying invisible.

If the automatic path missed a record, generateEmbedding queues it. It runs on the same delay as a write, about half a minute:

mutation { generateEmbedding(recordId: "rec_abc123", modelKey: "product") }
await foir.ns.search.generateEmbedding({ recordId: 'rec_abc123', modelKey: 'product' });

It needs embeddings:write, and the job is still skipped if content has not changed.

One model

Each model with embeddings gets a typed search<Model>s query returning { score, record }, where record is the model’s normal type. Scope: search:read:<model>.

query { searchProducts(query: "comfortable shoes for long walks", first: 5) { score record { _id title price } } }
const hits = await foir.product.search({ query: 'comfortable shoes for long walks', first: 5, });

Through the data client, record arrives with every scalar rather than the three selected above. Trim it with omit: ['description'] when payload size matters.

Across models

searchRecords spans every model that has embeddings. Scope: search:read. Pass modelKey to narrow it, which is the only filter it takes.

query { searchRecords(query: "return and refund information", first: 3) { recordId modelKey naturalKey score } }
const hits = await foir.ns.search.searchRecords({ query: 'return and refund information', first: 3, });

Namespace operations take no include or omit, so every hit carries recordId, modelKey, naturalKey, score and content.

A complete example

const SEARCH_QUERY = ` query SearchProducts($query: String!, $first: Int) { searchProducts(query: $query, first: $first) { score record { _id title } } } `; async function searchProducts(userQuery: string) { const response = await fetch('https://api.foir.dev/graphql', { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-api-key': process.env.FOIR_API_KEY!, }, body: JSON.stringify({ query: SEARCH_QUERY, variables: { query: userQuery, first: 10 }, }), }); const { data } = await response.json(); return data.searchProducts; } const results = await searchProducts('waterproof hiking boots'); // Matches on intent, so it finds products that never use those words.

Step 5: Search as the right person

Results are confined to what the caller would actually be served: their access, their locale, their targeted variants. A record they could not read never appears, and the score is never computed from text they would not see.

That confinement is automatic on the request’s own identity, so a user-authenticated call already searches as that user. Nothing extra to pass.

Where you do have to think is when your credential is making a search for someone other than itself, which is the normal shape for an agent. There, say who it is for:

  • pass the end user’s user_id and locale when the search is for them
  • pass targeting keys in context when the content has audience or geo-targeted variants
  • omit all three when you genuinely want an unpersonalised view across the corpus

Omitting them is not an error. You silently get the base, default-audience view, so a localised or personalised variant will never match and nothing will tell you why. That silence is the one sharp edge in this feature, and it is the reason to be deliberate here.

Passing a user_id personalises targeting only. It never widens reach, because reach comes from the credential making the call.

From an agent over MCP, this is foir_semantic_search with by_text, by_vector or similar_to_record, taking those same audience arguments.

Step 6: Scopes

What you are doingScope
Per-model search (search<Model>s)search:read:<model>
Cross-model search (searchRecords)search:read
Coverage and digest queries, _hasEmbeddingembeddings:read
Generate or write embeddingsembeddings:write

To change them, go to Settings > API keys, edit the key, add the scopes and save.

Note that embeddings:write also decides what appears on your generated client. A publishable key’s manifest lists the search reads alone, which makes the namespace look read-only; that is scope shaping rather than the namespace’s contents.

Tips

Interpreting scores

Each hit carries a score. Filter low-quality matches client-side.

ScoreQuality
0.9 to 1.0Near-exact semantic match
0.7 to 0.9Strong relevance
0.5 to 0.7Moderate relevance
Below 0.5Usually noise

Cap first at what you will actually display, and drop hits below a cutoff around 0.6 that you tune to your content.

Localised and personalised content

You do not need to embed each locale separately or manage variant coverage. The fan-out follows authored content: a locale with no translation of its own, or a variant inheriting its parent’s value, gets no embedding, and search resolves those back to the base content. So a project with ten locales and translations for two pays for two.

Auditing coverage

Useful when you generate vectors from your own service, or when you want to confirm a model is ready before putting search in front of users.

query { embeddingCoverage(modelKey: "note") { modelKey totalRecords embeddedRecords pendingRecords lastEmbeddedAt } }
const coverage = await foir.ns.search.embeddingCoverage({ modelKey: 'note' });

List exactly which records are missing an embedding, so you can fill only the gaps. It is the model’s own list, narrowed: an empty slot means any slot, and naming one checks just that slot. It needs embeddings:read beside the read of the records.

query { notes(missingEmbedding: "", first: 100) { edges { node { _id _naturalKey } } pageInfo { hasNextPage endCursor } totalCount } }
const missing = await foir.note.findMany({ missingEmbedding: '', first: 100, });

On a publishing model, remember that unpublished records are correctly counted as having nothing to embed. Pending is not always something to fix.

Bringing your own vectors

If you generate embeddings elsewhere, writeEmbeddings pushes them in directly, and embeddingDigests reads back the content hash stored with each one so you can skip anything unchanged:

query { embeddingDigests( modelKey: "note" key: "default" recordIds: ["rec_abc123", "rec_def456"] ) { recordId contentHash } }
const digests = await foir.ns.search.embeddingDigests({ modelKey: 'note', key: 'default', recordIds: ['rec_abc123', 'rec_def456'], });

Troubleshooting

SymptomLikely cause
A record never matchesIt is a draft on a publishing model, so it has nothing embedded
A record matched a moment ago and not nowIt was unpublished, which removes its embeddings
A translated or targeted variant never matchesThe search did not say who it was for, so it ran against the base view
Results are noisyAn identifier-shaped text field is embedded; switch off embed on it
A new record is not searchable yetEmbedding runs shortly after the write settles; give it about half a minute
Nothing in an existing model is searchableTurning the capability on does not backfill; run the priced backfill
Last updated on