Search
A search index kept up by triggers from config.recordTypes, search(q) as the caller, recents and favorites, and useCommandSearch for a Cmd+K dialog.
search keeps one search_documents row per searchable subject. Triggers
generated from each search entry in config.recordTypes write the row when the
source row changes, and search(q) reads the index as the caller: full-text
matches, prefixes while the user types and trigram matches for typos, filtered
to what the caller can read. With vector-search and embeddings, the results
fuse full-text and nearest-neighbour ranks.
better-supabase add searchimport { createSearch, searchSink } from "better-supabase/blocks/search";
import { useCommandSearch } from "@/hooks/use-search";The module needs tenant, permissions and subjects. It reads recents and
favorites from the per-user state of Share links
when that module is installed, and keeps embeddings when
vector search is installed and dimensions is
set.
Declare what to index
Give each subject a search entry. title defaults to the subject's
title column, and body lists the columns joined into the searchable body.
url and deletedAt come from the same registry entry.
recordTypes: {
note: {
table: "public.notes",
title: "title",
url: "/notes/{id}",
deletedAt: "deleted_at",
permissions: { read: "notes.read" },
search: { body: ["body", "summary"] },
},
customer: { table: "public.customers", title: "name", search: {} },
},
blocks: {
search: { options: { config: "english" } },
},| Option | Default | What it sets |
|---|---|---|
config | simple | The text search configuration for the tsvector and the query |
dimensions | none | The embedding size; with vector-search the index keeps an embedding column |
Each searched subject gets an after insert or delete or update trigger on
the columns the entry reads, so editing a column the index ignores writes
nothing. Subjects with tenant: false are skipped, because every document
belongs to a tenant. Installing the module indexes the rows that already
exist, and search.reindex() does it again after a config change.
Labels, descriptions and archived rows
A search entry takes five more keys for records whose label or matches live
outside their own row:
| Key | What it does |
|---|---|
description | A column whose value each hit returns as description (SearchHit.description), such as a SKU or the customer a record belongs to. The index adds a description column only once a subject sets it |
exclude | A column that keeps a row out of search while it is set (not null and not false), such as archived_at. Unlike deletedAt, the other blocks still see the row |
facets | Columns of the row (or of from) whose non-null values search_page filters on, such as ["customer_id", "status"]. The index keeps them in a facets jsonb column with a GIN jsonb_path_ops index, and a change to one re-indexes the record |
from | { view, key }: a view or table with one row per record, keyed by the record's id, that title, body, description and exclude read instead of the record's own row. The tenant, deletedAt and url still come from the record. Needs columns |
columns | Required with from: the columns of the record's own table the view reads. The generator cannot see what a view reads, so the config error names the record type when the list is missing. The update trigger fires only when one of those columns (or the id, tenant or deletedAt column) changes value, so an unrelated column costs no re-index. Doctor BS637 reports a column the view reads that the list leaves out. The drive's drive_node subject sets ["name"] |
watch | [{ table, key, via?, through?, columns? }]: tables whose insert, update or delete re-index the record. The update trigger lists key and columns, and its when clause skips a row when none of them changed. columns names the values the title or body reads from that table; without it, only a change to key re-indexes the record. key holds the record's id, or, with via, the value the record's via column holds. through: [{ table, from, to }] follows key across more tables first, such as a junction table: each hop reads to from the rows whose from holds the previous value |
records: {
customer: {
table: "public.customers",
idType: "uuid",
title: "name",
url: "/customers/{id}",
search: {
title: "label",
body: ["contact_names", "contact_emails", "city"],
description: "vat_number",
exclude: "archived_at",
from: { view: "public.customer_search_sources", key: "customer_id" },
columns: ["number", "name"],
watch: [
{
table: "public.customer_contacts",
key: "customer_id",
columns: ["name", "email"],
},
{
table: "public.customer_locations",
key: "customer_id",
columns: ["city"],
},
],
},
},
asset: {
table: "public.assets",
idType: "uuid",
search: {
title: "label",
description: "customer_name",
from: { view: "public.asset_search_sources", key: "asset_id" },
columns: ["serial_number", "product_id", "customer_id"],
watch: [
{
table: "public.products",
key: "id",
via: "product_id",
columns: ["name"],
},
],
},
},
},A source view is ordinary schema of the app: it expresses how a record is
labelled (a number and a title joined, a related name) without the block
knowing the shape. A change to one of the record's columns re-indexes it;
watch covers the tables behind the view. A watch without columns
re-indexes only when its key changes, so list the columns the view reads from
that table.
Imports
While an import run writes through import_upsert_batch, the index triggers
note each touched record once in better_supabase.import_search_dirty, and
finish_import_run (or cancel_import_run) indexes every noted record when
the run closes. A record that several batches of one run change is indexed
once, and a dry run notes nothing. Outside an import run, a write indexes its
records at once. A refresh that finds the same tenant, title, body, URL and
description leaves the document alone.
A record type that is written in large sets can set search.statement: true.
Its table then gets one statement trigger per insert, update and delete
instead of the row trigger, and each call reads the changed ids from the
statement's transition tables. An update re-indexes only the rows whose
watched columns changed. Write such a table in set-based statements, as the
fixture's public.import_customer_batch does: it inserts the new customers in
one statement and updates the changed ones in another, so a batch of any size
fires two search calls. Switching a type between row and statement triggers
renames its triggers, so run better-supabase upgrade and generate a
migration.
Watch triggers are plain create trigger statements on the watched table, so
the table has to exist when the file runs: an app table or a block table gets its
trigger from its own file, and a table the schema creates later needs the
trigger in your own SQL.
Search
search runs as the caller. The table's policy keeps the caller's tenants
(search.read), and can_subject drops each hit the caller can't read, so
a document is visible only where its source row is.
Server code calls the search instance on db, in the caller's organization. With gen.hooks set, better-supabase gen writes the hooks:
export const { useList: useSearch } = defineDataHooks(
"search",
(db: AppDb) => db.search,
);const hits = await db.search
.search("revnue plan", { types: ["note"], limit: 10 })
.orThrow();
// [{ subjectType: "note", subjectId, title, url, snippet, score }]"use client";
import { useSearch } from "@/lib/supabase/hooks";
const rows = useSearch({ limit: 50 });The query is lowercased and stripped of accents (unaccent), then matched
three ways: websearch_to_tsquery (quoted phrases, or, -word), each word
as a prefix, and trigram similarity on the title for typos. A trashed row
(its deletedAt column set) has no document, and a restored row gets it
back.
search ranks at most five times the requested page of candidates before it
checks what the caller may read. A document that only the trigram index matched
has no full-text rank, so it is scored by its title similarity alone. A
smaller limit per subject type was measured and did not change the time (ADR
0950).
| Hint | When |
|---|---|
SEARCH_QUERY_TOO_LONG | The query is longer than 256 characters |
SEARCH_SIGNED_OUT | touch or star without a signed-in user |
SEARCH_SUBJECT_UNKNOWN | refresh for a type without a search entry |
Browse and page
search_page returns one page as { items, nextCursor }, as the caller. Use it
for a list view; search stays the call for a command palette.
const first = await db.search
.page({
query: { types: ["customer"], filter: { status: "active" }, limit: 20 },
})
.orThrow();
const next = await db.search
.page({ query: { filter: { status: "active" }, after: first.nextCursor } })
.orThrow();Without q | With q |
|---|---|
Browses by the normalized title (sort_key), then subject_id, over an index on (tenant, subject_type, sort_key, subject_id). Items have no snippet and a null score. | Ranks like search (websearch, prefix and trigram) over at most 500 candidates, then pages by score, subject_type and subject_id. Scores are rounded to six decimals so the cursor compares exactly. |
filteris a JSON object, and a document matches when itsfacetscontain it (facets @> filter). A facet whose value is null is not stored, so it never matches.nextCursoris opaque and null on the last page. Pass it back asafterwith the sameq.- Like
search, the call keeps the caller's tenants and drops whatcan_subjecthides, so a page can come back with fewer rows than the limit only on the last page. search_pagedoes not use embeddings.
| Hint | When |
|---|---|
SEARCH_FILTER_INVALID | filter is not a JSON object |
SEARCH_CURSOR_INVALID | after is malformed, or comes from another query or mode |
Recents and favorites
touch records that the caller opened a subject and star stars it, both in
the share-links subject_user_state table. recents() and favorites()
list them newest first, with the title and URL from the index, and only for
subjects the caller can still read.
await search.touch("note", noteId);
await search.star("note", noteId);
const recent = await search.recents({ limit: 5 }).orThrow();Trash
Trashed rows drop out in one of two ways. A subject with a deletedAt
column needs nothing more: the trigger removes the document when the column
is set. A trash table that moves rows elsewhere emits events instead, and
searchSink turns them into index calls. Build search with a service
transport for it.
outbox.relay("search", searchSink(search));| Event | Action |
|---|---|
subject.trashed | remove |
subject.purged | remove |
subject.restored | refresh |
Pass on to map other event types. A subject type without a search entry
is skipped.
Embeddings
With dimensions set and vector-search installed, the index keeps an
embedding per document and clears it when the text changes. A partial index
on updated_at covers the documents without an embedding, so finding the
pending ones stays fast on a large index. A job embeds what is pending, through any function that returns one vector per text, such as the
AI SDK's embedMany:
await search.embedPending(async (texts) => {
const { embeddings } = await embedMany({ model, values: [...texts] });
return embeddings;
});
const hits = await search
.search(q, { embedding: await embedQuery(q) })
.orThrow();search then fuses the full-text and nearest-neighbour ranks by reciprocal
rank. setEmbedding skips a vector whose text changed since it was read.
Cmd+K
useCommandSearch is a registry item: npx shadcn add @better-supabase/use-search writes hooks/use-search.ts into the app. The
hook holds the state of a command dialog: Cmd+K and Ctrl+K
toggle it, the query is debounced, stale responses are dropped, and an empty
query shows favorites and recents. select records the item as opened and
closes the dialog.
The shortcut goes through the client's keyboard port: createClient from
better-supabase/client listens for keydown on the window, and React
Native has no keyboard port, so the hook runs there without one. Pass
shortcut: false to turn it off. The hook wraps
createCommandSearchController from better-supabase/blocks/search
(see block controllers).
const search = useCommandSearch({ organizationId });| Field | What it holds |
|---|---|
open, setOpen | The dialog state |
query, setQuery | The input |
groups | Favorites and recents, or the hits grouped by subject type |
loading, error | A query is running, and the last error |
select(item), star() | Records an open and closes; stars or unstars an item |
Vue
useBlockController from better-supabase/vue runs
createCommandSearchController with its options; the controller needs no
provider. state is a shallow ref of the snapshot and actions are the
controller's actions. The work starts on mount, and the controller is
disposed with the component.
<script setup lang="ts">
import { useBlockController, useSupabase } from "better-supabase/vue";
import {
createCommandSearchController,
createSearch,
rpcTransport,
} from "better-supabase/blocks/search";
const { organizationId } = defineProps<{ organizationId: string }>();
const supabase = useSupabase();
const { state } = useBlockController(
createCommandSearchController,
{
client: createSearch({ transport: rpcTransport(supabase) }),
organizationId,
},
false,
);
</script>
<template>
<ul>
<li v-for="hit in state.results ?? []" :key="hit.subjectId">
{{ hit.title }}
</li>
</ul>
</template>Pass keyboard: webKeyboard() from better-supabase/client to toggle the
dialog on Cmd+K.
Svelte
useBlockController from better-supabase/svelte runs
createCommandSearchController with its options; the controller needs no
provider. It returns a readable store of the snapshot, read with $,
with the actions on .actions. The work starts on mount, and the controller
is disposed with the component.
<script lang="ts">
import { betterSupabase, useBlockController } from "better-supabase/svelte";
import {
createCommandSearchController,
createSearch,
rpcTransport,
} from "better-supabase/blocks/search";
let { organizationId }: { organizationId: string } = $props();
const { supabase } = betterSupabase();
const search = useBlockController(createCommandSearchController, {
client: createSearch({ transport: rpcTransport(supabase) }),
organizationId,
}, false);
</script>
<ul>
{#each $search.results ?? [] as hit (hit.subjectId)}
<li>{hit.title}</li>
{/each}
</ul>Solid
useBlockController from better-supabase/solid runs
createCommandSearchController with its options; the controller needs no
provider. state() reads the snapshot through from, and actions are the
controller's actions. The work starts on mount, and the controller is
disposed with the owner.
import { For } from "solid-js";
import { useBlockController, useSupabase } from "better-supabase/solid";
import {
createCommandSearchController,
createSearch,
rpcTransport,
} from "better-supabase/blocks/search";
export function Component(props: { organizationId: string }) {
const supabase = useSupabase();
const { state } = useBlockController(
createCommandSearchController,
{
client: createSearch({ transport: rpcTransport(supabase) }),
organizationId: props.organizationId,
},
false,
);
return (
<ul>
<For each={state().results ?? []}>{(hit) => <li>{hit.title}</li>}</For>
</ul>
);
}With ReUI
The hook has no markup, so it drives any command component. With the ReUI
(shadcn) Command dialog:
"use client";
import { useRouter } from "next/navigation";
import { useCommandSearch } from "@/hooks/use-search";
import {
CommandDialog,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
} from "@/components/ui/command";
const LABELS: Record<string, string> = {
favorites: "Favorites",
recents: "Recent",
note: "Notes",
};
export function CommandSearch({ organizationId }: { organizationId: string }) {
const router = useRouter();
const search = useCommandSearch({ organizationId });
return (
<CommandDialog open={search.open} onOpenChange={search.setOpen}>
<CommandInput
value={search.query}
onValueChange={search.setQuery}
placeholder="Search"
/>
<CommandList>
<CommandEmpty>
{search.loading ? "Searching" : "No results"}
</CommandEmpty>
{search.groups.map((group) => (
<CommandGroup
key={group.key}
heading={LABELS[group.key] ?? group.key}
>
{group.items.map((item) => (
<CommandItem
key={`${item.subjectType}:${item.subjectId}`}
value={`${item.subjectType}:${item.subjectId}`}
onSelect={() => {
void search.select(item);
if (item.url) router.push(item.url);
}}
>
{item.title ?? item.subjectId}
</CommandItem>
))}
</CommandGroup>
))}
</CommandList>
</CommandDialog>
);
}cmdk filters items itself; set shouldFilter={false} on the Command
when the dialog lets you pass it, since the server already ranked them.
Hooks
before_search_document_index and after_search_document_index run around
each document write with the subject type and id. createSearch takes
hooks around its methods, as every block does.
Example
The Next.js example declares customer in config.recordTypes (deletedAt: "archived_at", so archived customers leave the index) and installs search
with api: "api". The header has a Search button that also opens on Cmd+K:
useCommandSearch({ schema: "api" }) drives a dialog that lists favorites and
recents for an empty query and customer matches as the user types. See
apps/examples/nextjs/src/features/search.
Without the client
db.search is this client. Code that does not go through bsb.db() builds it with a transport and an organization id:
const search = createSearch({ transport, service });
const hits = await search
.search("revnue plan", { types: ["note"], limit: 10 })
.orThrow();
// [{ subjectType: "note", subjectId, title, url, snippet, score }]Last updated on
Undo
Apply the undo tokens that block methods return, on the server with createUndo and in the browser with a useUndoStack for a toast's Undo button.
Approvals
Approval requests with steps per subject type and action, approvers by permission, role, team, user or the requester's manager, tenant policies that tighten the configured ones, confirm or authorize modes, single-use approvals bound to a request fingerprint, delegation, expiry and reminders.