Search
Use SearchPort when application code needs to index and query searchable read
models without depending on a specific search service.
Search indexes are application read models. Keep writes, authorization, and business invariants in your database and use search for discovery, filtering, sorting, facets, and ranking.
Define an index
Define index metadata near the feature that owns the searchable document:
// features/issues/search.ts
import { defineSearchIndex } from "@beignet/core/search";
export type IssueSearchDocument = {
id: string;
tenantId: string;
key: string;
title: string;
status: "open" | "resolved";
createdAt: string;
};
export const issueSearchIndex = defineSearchIndex<IssueSearchDocument>(
"issues",
{
searchableAttributes: ["key", "title"],
filterableAttributes: ["tenantId", "status"],
sortableAttributes: ["createdAt"],
displayedAttributes: ["id", "key", "title", "status"],
},
);Index documents
Use cases, listeners, jobs, and tasks can index documents through the same port:
import { waitForSearchOperation } from "@beignet/core/search";
await waitForSearchOperation(
ctx.ports.search,
await ctx.ports.search.configureIndex(issueSearchIndex),
);
const operation = await ctx.ports.search.indexDocuments(issueSearchIndex, {
id: issue.id,
tenantId: issue.tenantId,
key: issue.key,
title: issue.title,
status: issue.status,
createdAt: issue.createdAt,
});All writes, deletions, clears, and index configuration return a
SearchOperationResult. Memory search returns { status: "completed", affected }
(affected is omitted for configuration). Meilisearch returns
{ status: "accepted", taskIds }: acceptance does not prove indexing succeeded.
For durable indexing, use outbox-backed jobs or listeners after the database commit. In workers and backfills, explicitly wait before reporting success:
import { waitForSearchOperation } from "@beignet/core/search";
const search = ctx.ports.search;
await waitForSearchOperation(search, await search.configureIndex(issueSearchIndex));
const operation = await search.indexDocuments(
issueSearchIndex,
issues.map(issueToSearchDocument),
);
const completed = await waitForSearchOperation(search, operation, {
timeoutMs: 10_000,
pollIntervalMs: 100,
});
// completed.affected is the actual count when the provider reports one.waitForSearchOperation defaults to a 5-second overall timeout and 50 ms polling.
The deadline includes status requests. Both timing options must be integers
between 1 and 2,147,483,647 ms. Pass signal to stop waiting when a worker stops.
Failed or canceled tasks throw SearchOperationError with the task and provider
error. Timeout throws SearchOperationTimeoutError with the original operation;
it stops waiting but does not cancel remote work. Persist receipts for later
checks, or let a retryable job reindex current database state. Status-request
errors also propagate to the caller.
For nonblocking flows, inspect each operation.taskIds entry after narrowing
operation.status === "accepted" with search.getTask(id, { signal }).
Tasks expose pending, succeeded, failed, or canceled status and optional
affected/error details. These are provider task IDs, separate from Beignet's
application tasks. Synchronous memory search has no task IDs.
Meilisearch configuration retains both creation and settings tasks; an
index_already_exists creation result is treated as success for repeat setup.
Configuration replaces the four attribute lists: omitted searchable/displayed
lists reset to all fields, and omitted filterable/sortable lists reset to empty.
Query documents
const results = await ctx.ports.search.search(issueSearchIndex, {
query: "billing",
filters: {
tenantId,
status: "open",
},
sort: ["createdAt:desc"],
facets: ["status"],
limit: 20,
offset: 0,
});filters are provider-neutral exact-match filters. Providers translate them to
their native query language. Keep user authorization in use cases and policies;
include tenant or visibility filters when the index contains multi-tenant data.
Both memory and Meilisearch accept filters and facets only for fields declared in
filterableAttributes, and sort entries only for fields declared in
sortableAttributes. Map request input to app-owned allow-listed field names
before calling ctx.ports.search.search(...).
Non-2xx Meilisearch responses throw MeilisearchHttpError with the request
path, status, and response body. The adapter preserves plain-text or HTML
responses from proxies and gateways, so an upstream outage does not turn into
an unrelated JSON parse error.
Handle projected hits
Indexing still requires the full document type. Search results contain
SearchHit<TDocument> values: fields, including nested fields, are optional.
displayedAttributes can hide fields, and previously indexed documents may
predate the current shape. Both adapters apply the projection; [] returns
empty objects and an omitted list returns all stored fields. Filtering, sorting,
and facets still operate on indexed fields, including fields hidden from hits.
Dotted selections omit scalar ancestors and array entries that cannot reach the
selected field. Undefined properties are omitted. Selecting a field directly
still preserves its scalar value, null, or empty container.
Displayed attributes are not an authorization boundary: facets can expose hidden
values, and all tenant/visibility restrictions remain app-owned.
Validate hits against a result DTO before exposing required properties:
import { z } from "zod";
const hitSchema = z.object({
id: z.string(),
key: z.string(),
title: z.string(),
status: z.enum(["open", "resolved"]),
});
const hits = results.hits.flatMap((hit) => {
const parsed = hitSchema.safeParse(hit);
return parsed.success ? [parsed.data] : [];
});This example drops stale hits. Apps can instead fail explicitly and trigger a backfill. Search pagination totals count matching indexed documents before any app-level validation drops hits.
Setup with Meilisearch
Install the Meilisearch search provider:
bun add @beignet/provider-search-meilisearchRegister it in server/providers.ts:
import { createMeilisearchSearchProvider } from "@beignet/provider-search-meilisearch";
export const providers = [
createMeilisearchSearchProvider({
indexPrefix: "my-app",
}),
];Set MEILISEARCH_HOST in production. Optional env vars include
MEILISEARCH_API_KEY, MEILISEARCH_INDEX_PREFIX, and
MEILISEARCH_TIMEOUT_MS.
The timeout must be an integer from 1 through 2,147,483,647 milliseconds, the JavaScript timer range. Search instrumentation records the index, result count, and query length; it does not record query text or document bodies.
The provider contributes ctx.ports.search and ctx.ports.meilisearch as an
escape hatch with the raw client and configured index prefix.
Testing
createTestPorts(...) includes an in-memory search port by default:
const { ports, search } = createTestPorts<AppPorts>();
await ports.search.indexDocuments(issueSearchIndex, issueDocument);
await expect(
search.search(issueSearchIndex, {
query: "billing",
filters: { tenantId: "tenant_example" },
}),
).resolves.toMatchObject({
hits: [{ id: issueDocument.id, key: issueDocument.key, title: issueDocument.title, status: issueDocument.status }],
});Memory search enforces the same attribute allow-lists and displayed-field projection, and completes writes synchronously. It remains a substring-search test adapter, not a simulation of Meilisearch ranking, tokenization, or timing. Test asynchronous failures with a port that returns an accepted receipt and a failed task. Cover both indexing jobs and backfills.
You can also import the memory adapter directly:
import { createMemorySearch } from "@beignet/core/search";
const search = createMemorySearch();Memory search is per-process. Documents indexed by a seed script are invisible to a dev server running
createMemorySearchProvider()— they are different processes. Rebuild the index inside the serving process with a backfill task or outbox-driven sync listeners, or use@beignet/provider-search-meilisearchso both processes share one store. See Process boundaries of memory providers.
API reference
Related pages
- Ports and adapters for app-facing dependency boundaries.
- Tasks for search backfills.
- Outbox for durable post-commit indexing.
- Providers for provider setup and escape hatches.