Hybrid search
Turn a table into a searchable one with one call. You get keyword search (BM25 ranking, or Postgres full-text search as a fallback), optional vector search, and a fusion of both (Reciprocal Rank Fusion, RRF). It runs as the caller, so Row Level Security decides which rows can be found. Community only needs SQL; there is no extra service.
Turn it on
Section titled “Turn it on”As the table owner (the SQL editor works; the anon, authenticated and service_role API roles cannot):
select base.enable_search('public.docs', '{title,body}'); -- keyword search on two columnsselect base.enable_search('public.docs', '{title,body}', 'embedding'); -- plus vector search on a vector(n) columnselect base.enable_search('public.docs', '{title,body}', null, '{"language":"english","weights":{"title":3,"body":1}}'); -- stemming and column weightsselect base.disable_search('public.docs'); -- removes functions and the indexes Base made- The table needs a primary key. Columns are
text,varcharorcitext(1 to 8). Partitioned tables and theaudit,auth,base,storage,realtime,extensionsandpg_*schemas are not supported. - Backend:
bm25(onebm25index per column, extensionpg_textsearch, enabled for you) when it can be created, elsefts(one GIN index per column onto_tsvector(config, col); no generated column, the table is not rewritten). Force one with{"backend":"bm25"}or{"backend":"fts"}. The result says which one was used. - With a vector column it also creates a cosine HNSW index, unless the column already has an
hnsworivfflatindex of yours (then yours is used; it must usevector_cosine_ops). HNSW needsvector(n)withn <= 2000. - Calling it again is safe. Changing the language or backend rebuilds the indexes. The result lists
findings(no vector column, index skipped, large table). - Index creation is not
CONCURRENTLY: it blocks writes while it runs. On big tables run it in a quiet period. In Docker, the default/dev/shmcan be too small for a parallel HNSW build; setmax_parallel_maintenance_workers = 0or raiseshm_size. - Dropping a table that has search needs
disable_searchfirst (orDROP ... CASCADE). Renaming the table or a column regenerates the functions; dropping a searchable column switches search off with a warning.
Search
Section titled “Search”It creates two functions next to the table (for public.docs):
base_search_docs(p_query, p_embedding, p_limit, p_offset, p_opts)returns the table’s rows, best first. PostgREST filters (select, column filters,order) apply on top, so use it through the RPC endpoint.base_search_docs_scored(...)returns(rec docs, score float8, ranks jsonb);ranksis{"keyword": 1, "vector": 3}.
From the SDK, base.search(table, options) wraps these functions and validates the options before it sends anything (it throws a RangeError on bad input):
import { createClient } from '@potalab/base'const base = createClient({ url, key })
const { data } = await base.search('docs', { q: 'kubernetes pods', limit: 10 })// hybrid: send the query embedding yourself (Community does not call a model); filters chain like any queryawait base.search('docs', { q: 'reset password', vector: queryVector, limit: 10 }).eq('lang', 'en')// score and rank per branch: rows are { rec, score, ranks }const { data: scored } = await base.search('docs', { q: 'reset password', vector: queryVector, scored: true })| Option | Meaning |
|---|---|
q, vector |
Words and/or the query embedding. At least one |
limit, offset |
1 to 100 (default 10), 0 to 1000 |
mode |
hybrid (default), keyword or vector |
weights, rrfK, candidates, minScore |
Tuning, same as p_opts (weights, rrf_k, candidates, min_score) |
scored |
Use base_search_<table>_scored and return { rec, score, ranks } |
The same calls through the generic RPC, which is what base.search sends:
const { data: viaRpc } = await base.rpc('base_search_docs', { p_query: 'kubernetes pods', p_limit: 10 })// hybrid: send the query embedding yourself (Community does not call a model)await base.rpc('base_search_docs', { p_query: 'reset password', p_embedding: queryVector, p_limit: 10 })// only vectors, or only keywordsawait base.rpc('base_search_docs', { p_embedding: queryVector, p_opts: { mode: 'vector' } })await base.rpc('base_search_docs', { p_query: 'SKU-4412', p_opts: { mode: 'keyword' } })p_query uses web-search syntax ("exact phrase", -excluded, or); characters that would break a tsquery are harmless.
p_embedding is an array of numbers; the wrong length raises 22000. If the table has no vector column, an embedding is ignored
in hybrid mode and mode: 'vector' raises 22023.
p_opts key |
Default | Meaning |
|---|---|---|
mode |
hybrid |
hybrid (uses what you send), keyword, vector |
weights |
first column 1, second 1/2, third 1/3 … | {"title": 3, "vector": 2}: weight of a column’s ranking in the fusion |
rrf_k |
60 | RRF constant (1 to 1000) |
candidates |
max(50, 5 * limit), at most 200 |
rows each branch fetches before fusion |
min_score |
0 | drop fused scores below this |
Unknown keys raise 22023. p_limit is 1 to 100 (default 10), p_offset 0 to 1000, the query at most 1000 characters (54000).
Only candidates are ranked, so a page beyond the candidates is empty.
How the score works. Each branch (every keyword column, and the vector column) ranks its candidates; a row’s score is the sum of
weight / (rrf_k + rank) over the branches it appears in. A row at keyword rank 1 and vector rank 3 scores 1/61 + 1/63. Raw BM25 and
cosine numbers are never mixed, so they need no normalizing. A row found by one branch only still counts.
Row Level Security
Section titled “Row Level Security”The functions are SECURITY INVOKER: every branch is a query as the caller, so the policies and grants on the table apply and rows the caller
cannot read are never returned and never influence the order the caller sees. anon gets no rows when no policy lets it in. The
functions give no privileges: a role without SELECT on the table gets permission denied.
Three things to know:
- Selective policies and
auth.uid().auth.uid()is inlined by the planner (about 3 microseconds a call, was about 33), soowner = auth.uid()is now a reasonable policy and needs no special form. It is still evaluated for every row the scan examines, and the vector scan examines thousands of rows when you see 1% of a table, so for very selective policies on large tablesowner = (select auth.uid())(evaluated once) remains faster, though no longer required. Measured (64-dim vectors,bm25, limit 10, hybrid p95): 1% visible 134 ms at 10,000 rows and 288 ms at 100,000 rows withauth.uid(), against 14 ms and 89 ms with(select auth.uid()); at 10% visible 88 / 84 ms against 19 / 84 ms (see the bench). The vector branch also chooses its path per call: when the planner expects the caller to see at most 10% of the table (and at most 20,000 rows) and the policy is cheap (a column filter or(select auth.uid())), the visible rows are ranked exactly, otherwise HNSW runs with an iterative scan. Both only ever return rows the caller can see. Lowercandidates, or give each tenant a leading filter column and an index, for further gains. ftsunder RLS scans the table. Postgres will not use a GIN index through@@once a row-level security policy applies to the caller, so theftsfallback reads the table and computesto_tsvectorfor the rows the caller can see: about 10 to 65 ms for 10,000 rows and 140 to 560 ms for 100,000 rows (1% to 10% visible) with(select auth.uid()), up to about a second withauth.uid(). Usebm25(the default) for tables with RLS;enable_searchreports the findingfts_scans_under_rls.- Side channel. BM25 statistics (document frequency, average length) are computed over the whole index, hidden rows included, so a visible row’s raw BM25 score depends slightly on rows you cannot see. The fusion uses ranks only and the functions never return raw scores. Treat the exact order of near-equal rows as non-secret.
Limits of P1
Section titled “Limits of P1”No endpoint sugar (POST /search/v1), no SDK method, no dashboard tab, no explain, no highlight, no model calls (Community does not embed:
Cloud’s /semantic/v1/search embeds the question for semantic columns), one table per call. These are phase 2 and 3 of
the design notes. Vietnamese has no stemmer: use simple (the default), which splits on spaces.