Part of AI in CanadaAI · Search

Semantic and hybrid search for your site or app, in Postgres.

Put full-text search and vector search in the same Postgres table, merge their rankings with reciprocal rank fusion in one SQL query, and let a background job fill in the vectors. With the bge-m3 model, a French question finds the English page that answers it. Below: the schema, the job, the query, a search function that degrades to keyword search, and what each approach got right on a labelled test set. On our test set vectors alone matched or beat hybrid, so measure before you keep the keyword half.

Facts checked

What you’ll build

A search box for a help centre, a documentation site, a product catalogue or an internal knowledge base. Everything lives in one table: the page text, a generated tsvector column for keyword search, and a vector(1024) column holding the page’s bge-m3 embedding. The app calls Canner’s AI endpoint twice: once per page, in the background, when the text changes; and once per search, to embed the query.

We built it end to end against the real endpoint with a 34-article bilingual help centre for an imaginary bike shop: shipping, returns, billing error codes, e-bike batteries, some articles in French and a few near-duplicates. Every query and number on this page comes from that test.

Set up: Dedicated Postgres, pgvector and an AI endpoint

pgvector needs the Dedicated Postgres add-on: on the shared cluster only Canner can install extensions. Create an AI endpoint that may use bge-m3 and attach it to the project; the next deploy injects OPENAI_BASE_URL and OPENAI_API_KEY, so the OpenAI SDK works without configuration. You can do both from the dashboard (Database → Extensions, AI) or the CLI.

# Dedicated Postgres add-on first: only it can install extensions
canner db extensions <database> install vector
canner ai create site-search --models bge-m3
canner ai attach site-search      # in the project folder
canner redeploy                   # the app now has OPENAI_BASE_URL and OPENAI_API_KEY

One table for keywords and vectors

The lang column is a regconfig, so each row is stemmed with its own language: “livraisons” and “livraison” match in French, “deliveries” and “delivery” in English. Titles get weight A so a match in the title ranks above one in the body. The embedding column is nullable on purpose: a page is saved immediately and becomes keyword-searchable at once, and the job adds its vector a few seconds later. The trigger clears the vector when the title or body changes, and only then.

CREATE EXTENSION IF NOT EXISTS vector;

CREATE TABLE documents (
  id          bigserial PRIMARY KEY,
  url         text NOT NULL UNIQUE,
  lang        regconfig NOT NULL DEFAULT 'english',   -- 'english' or 'french'
  category    text NOT NULL,
  title       text NOT NULL,
  body        text NOT NULL,
  tsv         tsvector GENERATED ALWAYS AS (
                setweight(to_tsvector(lang, title), 'A') ||
                setweight(to_tsvector(lang, body), 'B')) STORED,
  embedding   vector(1024),        -- bge-m3; NULL until the background job fills it
  updated_at  timestamptz NOT NULL DEFAULT now()
);

CREATE INDEX documents_tsv ON documents USING gin (tsv);
CREATE INDEX documents_embedding ON documents USING hnsw (embedding vector_cosine_ops);

-- When the text changes, clear the vector so the job embeds it again
CREATE FUNCTION documents_reembed() RETURNS trigger AS $$
BEGIN
  IF NEW.title IS DISTINCT FROM OLD.title OR NEW.body IS DISTINCT FROM OLD.body THEN
    NEW.embedding := NULL;
    NEW.updated_at := now();
  END IF;
  RETURN NEW;
END $$ LANGUAGE plpgsql;

CREATE TRIGGER documents_reembed BEFORE UPDATE ON documents
  FOR EACH ROW EXECUTE FUNCTION documents_reembed();

Index new content in a background job

Saving a page never waits for the model. The app writes the row; a job picks up every row without a vector, embeds up to 64 at a time in one request, and writes the vectors back. bge-m3 returns normalised vectors of 1,024 numbers, and pgvector accepts them as JSON text.

-- Your CMS, admin page or import script saves pages like this. No model call here.
INSERT INTO documents (url, lang, category, title, body)
VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (url) DO UPDATE
  SET lang = EXCLUDED.lang, category = EXCLUDED.category,
      title = EXCLUDED.title, body = EXCLUDED.body;

The embedding job

The models answer one request at a time across the service, and a request can wait its turn for up to 2 minutes or get 429 server_busy when too many are queued. That is fine for a job and wrong for a page save, which is why the vector is filled in afterwards. The updated_at check keeps a slow batch from writing an old vector over a page someone edited in the meantime: in our test, a page edited while its batch was with the model stayed pending and was embedded on the next tick.

  • In the web process with setInterval, as above, for a steady trickle of edits. On Starter a project sleeps after 3 hours without visitors and the timer sleeps with it, but nothing new is saved while it sleeps either.
  • As a separate Worker project for a first import of thousands of pages, so the backfill doesn’t share memory with your web server (worker projects, background jobs). It reaches the same database through its DATABASE_URL.
  • Re-embed only what changed. The trigger ignores edits that don’t touch the text, and an identical re-save doesn’t clear the vector: in our test, upserting the same text twice left nothing pending.
// embed-worker.js: fills in vectors for new and edited rows
import OpenAI from "openai";
import pg from "pg";

const ai = new OpenAI({ maxRetries: 4 });   // retries 429 server_busy and 503 with backoff
const db = new pg.Pool({ connectionString: process.env.DATABASE_URL, max: 2 });
const BATCH = 64;                            // texts per request (the endpoint takes up to 128)

async function embedPending() {
  const { rows } = await db.query(
    `SELECT id, title, body, updated_at::text AS version
     FROM documents WHERE embedding IS NULL ORDER BY id LIMIT $1`, [BATCH]);
  if (rows.length === 0) return 0;

  const r = await ai.embeddings.create({
    model: "bge-m3",
    input: rows.map((d) => `${d.title}\n\n${d.body}`),
  });
  for (const e of r.data) {
    const d = rows[e.index];
    // skip a row that was edited while we waited for the model: it is pending again
    await db.query(
      "UPDATE documents SET embedding = $2 WHERE id = $1 AND updated_at = $3::timestamptz",
      [d.id, JSON.stringify(e.embedding), d.version]);
  }
  return rows.length;
}

let running = false;
export async function tick() {
  if (running) return;                       // one batch at a time
  running = true;
  try {
    while ((await embedPending()) === BATCH); // keep going while there is a backlog
  } catch (err) {
    console.error("embedding failed, next tick retries:", err.status ?? err.message);
  } finally {
    running = false;
  }
}

setInterval(tick, 30_000);                   // or run this file on its own as a Worker project

The search query: full-text and vectors, merged with RRF

Each half returns its 20 best rows with their rank. Reciprocal rank fusion adds 1 / (60 + rank) from each list a row appears in, so a row near the top of both lists wins, and the two scores never need to be on the same scale. 60 is the constant in pgvector’s own hybrid search example.

  • `websearch_to_tsquery` never raises a syntax error, so the raw search box text can go straight in, and it understands quoted phrases, or and -word. Every other word must match, which keeps the keyword half precise.
  • Both stemmers: the query is parsed once as English and once as French and either may match, so you don’t need to guess the language of a three-word query.
  • The HNSW index serves the ORDER BY embedding <=> $1 LIMIT 20 part. If you add a WHERE filter (one site, one customer), read the filtering trap first: approximate indexes filter after the scan and can return fewer rows than you asked for.
-- $1 = the query's embedding as '[0.01, -0.03, ...]', $2 = the query as typed
WITH keyword AS (
  SELECT d.id, row_number() OVER (ORDER BY ts_rank_cd(d.tsv, q) DESC) AS r
  FROM documents d,
       (SELECT websearch_to_tsquery('english', $2) || websearch_to_tsquery('french', $2)) AS x(q)
  WHERE d.tsv @@ q
  ORDER BY r
  LIMIT 20
),
semantic AS (
  SELECT id, row_number() OVER (ORDER BY embedding <=> $1) AS r
  FROM documents
  WHERE embedding IS NOT NULL
  ORDER BY embedding <=> $1
  LIMIT 20
)
SELECT d.id, d.url, d.title,
       coalesce(1.0 / (60 + s.r), 0) + coalesce(1.0 / (60 + k.r), 0) AS score
FROM semantic s
FULL OUTER JOIN keyword k USING (id)
JOIN documents d USING (id)
ORDER BY score DESC
LIMIT 10;
Building blockWhat it does here
ts_rank_cd †Ranks keyword matches by how close and how frequent the matched words are
<=> †Cosine distance, the operator that matches vector_cosine_ops and bge-m3’s normalised vectors
Reciprocal rank fusion †Merges the two ranked lists, k = 60
pg_trgm % †Trigram similarity above 0.3 by default; used for typo suggestions below

† Competitor details come from each vendor’s own published pages on the dates shown; prices and plans change, so check the vendor before you decide. `ts_rank_cd` (2026-11-23) · `<=>` (2026-11-23) · Reciprocal rank fusion (2026-11-23) · `pg_trgm` `%` (2026-11-23)

Calling it from the app, with a keyword fallback

Embedding a short query takes about a second or less of model time, but your request waits its turn when the service is busy. A search box shouldn’t hang, so the function gives the embedding 10 seconds, without retries, and falls back to keyword search if it doesn’t come back. During our tests, while other work filled the queue, some query embeddings did time out, and the fallback answered from the keyword index instead. Repeated queries come from the cache and never reach the model.

// search.js
import OpenAI from "openai";
import pg from "pg";
import { HYBRID_SQL } from "./sql.js";       // the query above

const KEYWORD_SQL = `
SELECT id, url, title
FROM documents,
     (SELECT websearch_to_tsquery('english', $1) || websearch_to_tsquery('french', $1)) AS x(q)
WHERE tsv @@ q
ORDER BY ts_rank_cd(tsv, q) DESC
LIMIT 10`;

const db = new pg.Pool({ connectionString: process.env.DATABASE_URL, max: 8 });
const ai = new OpenAI({ timeout: 10_000, maxRetries: 0 }); // a search box can't wait for the queue
const cache = new Map();   // query -> vector; popular queries cost nothing after the first

async function embedQuery(q) {
  const key = q.trim().toLowerCase();
  if (cache.has(key)) return cache.get(key);
  const r = await ai.embeddings.create({ model: "bge-m3", input: key });
  const vec = JSON.stringify(r.data[0].embedding);
  cache.set(key, vec);
  if (cache.size > 5000) cache.delete(cache.keys().next().value); // drop the oldest
  return vec;
}

export async function search(q) {
  let vec = null;
  try {
    vec = await embedQuery(q);
  } catch (err) {
    console.warn("embedding unavailable, keyword search only:", err.status ?? err.message);
  }
  const { rows } = vec
    ? await db.query(HYBRID_SQL, [vec, q])
    : await db.query(KEYWORD_SQL, [q]);
  return rows;
}

French questions, English pages

bge-m3 puts English and French in the same vector space, so one index serves both languages. In our test, every one of these found the right article first, and the keyword half of the query found none of them, because they share no words with the answer:

  • “combien de temps pour être remboursé” → the English article “Refund timing”.
  • “facture avec TPS et TVQ” → “Getting an invoice with GST and QST”.
  • “recharger la batterie du vélo électrique quand il fait froid” → “Charging an e-bike battery in the cold”.
  • “rust on chain from road salt” → the French article “Entretien de la chaîne en hiver”.

What we measured: is hybrid better than vectors alone?

We labelled 26 queries with the article that answers them: 12 ordinary questions (4 of them crossing languages), 11 error-code lookups such as “PAY-409” among a dozen near-identical error pages, and 3 typos. The table counts how often the right article came first.

  • Vectors alone were best on our set. bge-m3 even told the error codes apart and shrugged off “pasword resset” and “studed tirs”.
  • An any-word keyword half made hybrid worse: common words matched the wrong articles and outvoted the vector ranking. Requiring every word keeps the keyword half quiet unless it is sure.
  • The one miss of the query above: “where is my package” put “Returning an item” first, because English stemming turns “packaging” and “package” into the same word. The right article was second.
  • Why keep the keyword half anyway: a page is findable by keyword the moment it is saved, before its vector exists; people can search for an exact phrase in quotes ("PAY-409" returned only its own page); it keeps working when the model is busy; and the margins on codes were thin (for “error PAY-415” the right page’s cosine similarity was 0.648 and the next page’s 0.644). If your content has product names or jargon the model never saw, keyword matches carry more weight.
MethodQuestions (12)Error codes (11)Typos (3)
Keyword, every word must match2100
Keyword, any word may match6100
Vectors only (bge-m3)12113
Hybrid, any-word keyword half9113
Hybrid, the query above11113

Typos: vectors cope, pg_trgm suggests

In our test the vector half found the right article for every misspelled query, while keyword search found nothing. If you also want a “Did you mean …?” line, or typo tolerance in keyword-only mode, pg_trgm can correct each word against the words that appear in your pages, the approach the pg_trgm documentation describes. % uses a similarity threshold of 0.3 by default. On our test pages it turned “pasword resset” into “password reset”, “studed tirs” into “studded tires”, “chane” into “chaîne” and “delivary” into “delivery”, and left a word it had never seen unchanged.

-- canner db extensions <database> install pg_trgm
CREATE EXTENSION IF NOT EXISTS pg_trgm;

CREATE TABLE search_words (word text PRIMARY KEY);
CREATE INDEX search_words_trgm ON search_words USING gin (word gin_trgm_ops);

-- Refresh after content changes (the embedding job is a good place)
BEGIN;
TRUNCATE search_words;
INSERT INTO search_words
  SELECT word FROM ts_stat('SELECT to_tsvector(''simple'', title || '' '' || body) FROM documents');
COMMIT;

-- "Did you mean": replace each word of $1 with the closest known word
SELECT string_agg(coalesce(
         (SELECT w.word FROM search_words w
          WHERE w.word % t.token
          ORDER BY similarity(w.word, t.token) DESC
          LIMIT 1),
         t.token), ' ' ORDER BY t.n) AS suggestion
FROM unnest(regexp_split_to_array(lower(trim($1)), '\s+')) WITH ORDINALITY AS t(token, n);

When keyword search alone is enough

  • People search for exact things: part numbers, SKUs, names, invoice numbers, error codes on a small site. Postgres full-text search with websearch_to_tsquery, plus pg_trgm for typos, needs no model and no AI endpoint.
  • Your visitors use your words. If the titles are what people type (“Return policy”, “Shipping”), semantic search adds little.
  • One language, short catalogue, few searches a day. Measure before you add moving parts.
  • Semantic search earns its place when people describe a problem in their own words, when they ask in the other official language, or when the answer is in the body of a long page rather than in its title.

Running it on Canner

The pages, the vectors and the index stay in your Postgres database in Montréal. The page text and the search queries are processed in memory on Canner’s server in Montréal to compute embeddings and are not stored, not sent to another company and not used for training. Embeddings aren’t checked by the content-safety model, so no search is ever blocked.

Usage is measured in model time, with a monthly allowance per plan: see AI endpoints for current allowances. Embeddings are among the lightest requests. To keep usage down: batch texts (up to 128 per request), re-embed only changed pages, cache query embeddings, and set a requests-per-minute limit on the endpoint so a bug can’t loop.

Questions

What is hybrid search in Postgres?

Running full-text search (tsvector) and vector search (pgvector) on the same table and merging the two ranked lists, usually with reciprocal rank fusion: each row scores 1 / (60 + rank) in each list it appears in, and the sum decides the order.

Can a French query find English content?

Yes, with a multilingual embedding model like bge-m3. In our test, French questions found the English articles that answered them first every time. Keyword search can’t do this, since the words differ.

Do I need a separate vector database?

Not for a site or app search. pgvector keeps vectors in the same rows as the text, so one query does keyword and vector search, and backups cover both. Look at a dedicated service only at very large scale.

Does pgvector work on Canner’s shared Postgres?

No. pgvector needs the Dedicated Postgres add-on; install it with canner db extensions <database> install vector or from Database → Extensions.

What happens if the AI endpoint is busy during a search?

With the search function above, the query embedding gets 10 seconds; if it doesn’t arrive, the search runs on the keyword index alone. New pages are keyword-searchable immediately and get their vectors from the background job.

Search in English and French, hosted in Montréal.

Add Dedicated Postgres, install pgvector, and attach an AI endpoint with bge-m3. See AI endpoints.