Part of AI in CanadaAI · Recommendations

Related items, recommendations and reranking with embeddings.

Once your pages or products have embeddings in Postgres, “related articles”, “similar products” and “because you read” are nearest-neighbour queries that cost no model time at all. This guide shows the SQL, how to measure a near-duplicate threshold on your own data, a nightly job that precomputes the lists, and what happened when we tried to rerank search results with a language model: on our test set it made them worse.

Facts checked

Start from the search table

Everything here assumes the documents table from semantic and hybrid search: one row per page or product, a lang, a category, and a vector(1024) column filled by a background job with bge-m3 embeddings from a Canner AI endpoint. pgvector needs the Dedicated Postgres add-on.

We ran every query on the same bilingual test set: 34 help-centre articles for an imaginary bike shop, including an article rewritten twice, two articles that exist in English and French, and a dozen payment-error pages written from one template. The vectors came from the real endpoint; the numbers below are what we measured.

The plain version is one line of pgvector: order the other rows by distance to the current one (nearest neighbours to a row). In practice the top results are often useless: the same article in the other language, an older rewrite of it, or five near-identical pages from one category. The query below excludes the article itself, keeps the reader’s language, skips near-duplicates, and allows at most two results per category.

  • For “Shipping times within Canada” the plain nearest neighbours were its rewrite (0.936) and its French translation; the query above returned “Returning an item”, “Refund timing”, “Tracking your parcel” and “Shipping to the United States” instead.
  • For “Card declined: error PAY-402” the plain list was five other error pages. The category cap kept two and brought in “Refund timing” and “Changing your email address”. Whether that is better depends on your site: raise the cap where readers browse within a category.
  • The index is used: the subquery form makes the target vector a constant, so Postgres runs an HNSW index scan (we checked with EXPLAIN).
-- $1 = the article being read
WITH nearest AS (
  SELECT id, url, title, category,
         embedding <=> (SELECT embedding FROM documents WHERE id = $1) AS distance
  FROM documents
  WHERE id <> $1                                          -- not itself
    AND lang = (SELECT lang FROM documents WHERE id = $1) -- same language
    AND embedding IS NOT NULL
  ORDER BY embedding <=> (SELECT embedding FROM documents WHERE id = $1)
  LIMIT 30
),
capped AS (
  SELECT *, row_number() OVER (PARTITION BY category ORDER BY distance) AS nth
  FROM nearest
  WHERE distance > 0.10              -- near-duplicate: skip (see below)
)
SELECT id, url, title, round((1 - distance)::numeric, 3) AS similarity
FROM capped
WHERE nth <= 2                       -- at most two from one category
ORDER BY distance
LIMIT 5;

Similar products in the same category, and “because you read”

For a catalogue, “similar items” usually means same category. Filtering on an approximate index returns fewer rows when the category is small, because the filter runs after the index scan: pgvector 0.8.0 and later can keep scanning with SET hnsw.iterative_scan = strict_order (details).

-- Similar products: same category only
SELECT id, url, title
FROM documents
WHERE id <> $1
  AND category = (SELECT category FROM documents WHERE id = $1)
  AND embedding IS NOT NULL
ORDER BY embedding <=> (SELECT embedding FROM documents WHERE id = $1)
LIMIT 4;

Recommendations from what a visitor read

Average the vectors of the last few things a visitor read and look for the nearest unread items. pgvector supports avg() on vectors. In our test, a visitor who read the two e-bike battery articles was offered winter storage, lights and the sizing chart; one who read three payment-error pages was offered more payment-error pages. Add the same lang filter as above if both languages are in the table: a visitor who read “Returning an item” and “Refund timing” was offered the French version of the returns article first.

-- "Because you read": $1 = ids the visitor read recently
SELECT id, url, title
FROM documents
WHERE id <> ALL($1::bigint[])
  AND embedding IS NOT NULL
ORDER BY embedding <=> (SELECT avg(embedding) FROM documents WHERE id = ANY($1::bigint[]))
LIMIT 5;
Querypgvector feature
Related to one row †Nearest neighbours with a subquery as the target
Because you read †avg(embedding) as the target
Category filter †Iterative index scans (0.8.0+) so filtered queries return enough rows

† 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. Related to one row (2026-11-23) · Because you read (2026-11-23) · Category filter (2026-11-23)

Near-duplicate detection, and picking your threshold

Duplicates show up as pairs with a very high cosine similarity. No number works for every model and every site, so measure: list the closest pairs, mark each one as a duplicate or not, and put your cutoff between the lowest real duplicate and the highest pair that isn’t one. Here are the closest pairs in our test set (similarity = 1 − cosine distance):

  • Within one language the only duplicate scored 0.936 and the closest non-duplicate 0.869, so a cutoff of 0.90 (a cosine distance of 0.10, as in the query above) separated them cleanly.
  • Translations score lower than rewrites (0.883 to 0.927 here) and overlap with template pages. On a bilingual site, compare within a language, and link translations explicitly rather than detecting them.
  • Template pages are the trap. Pages that share most of their wording score close to duplicates. Look at your closest pairs before you trust a number, and recheck after big content changes. Across all 561 pairs in our set, the median similarity was 0.44.
  • Check on save: when the embedding job fills a new row, look up its nearest neighbour and flag it for an editor if it is above your cutoff.
-- The 50 closest pairs, from each article's 5 nearest neighbours (uses the HNSW index)
SELECT a.id AS a_id, b.id AS b_id, a.title AS a_title, b.title AS b_title,
       a.lang = b.lang AS same_language,
       round((1 - (a.embedding <=> b.embedding))::numeric, 3) AS similarity
FROM documents a
CROSS JOIN LATERAL (
  SELECT id, title, lang, embedding FROM documents
  WHERE id <> a.id AND embedding IS NOT NULL
  ORDER BY embedding <=> a.embedding
  LIMIT 5
) b
WHERE a.embedding IS NOT NULL AND a.id < b.id
ORDER BY similarity DESC
LIMIT 50;
PairSame language?SimilarityDuplicate?
Shipping times within Canada / How long delivery takes in Canada (rewrite)Yes0.936Yes
Shipping times within Canada / Délais de livraison au CanadaNo0.927Translation
Returning an item / Retourner un articleNo0.897Translation
Délais de livraison au Canada / How long delivery takes in CanadaNo0.883Translation
Card declined: error PAY-402 / error PAY-409Yes0.869No: same template, different error
Card declined: error PAY-409 / Payment error PAY-401Yes0.813No

Precompute the lists in a scheduled job

Related lists change only when content changes, so compute them once and read them with a primary-key lookup. The refresh runs entirely in Postgres on vectors you already have: it uses no model time. On our 34 articles it took a few dozen milliseconds; it grows linearly with the number of articles, one index lookup each.

CREATE TABLE related_articles (
  article_id  bigint NOT NULL REFERENCES documents(id) ON DELETE CASCADE,
  rank        int    NOT NULL,
  related_id  bigint NOT NULL REFERENCES documents(id) ON DELETE CASCADE,
  similarity  real   NOT NULL,
  PRIMARY KEY (article_id, rank)
);

-- What the article page reads: a primary-key lookup, no vector maths
SELECT d.url, d.title
FROM related_articles ra
JOIN documents d ON d.id = ra.related_id
WHERE ra.article_id = $1
ORDER BY ra.rank;

The refresh endpoint

Create a scheduled job in Compute → New job that calls /jobs/refresh-related, for example every day at 04:00 UTC (0 4 * * *). The handler answers at once and does the work afterwards, so a long refresh never times out the call. The whole refresh is one transaction: pages keep showing yesterday’s lists until the new ones are complete.

// refresh-related.js
import express from "express";
import pg from "pg";
import { RELATED_SQL } from "./sql.js";   // the related-articles query above

const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL, max: 4 });

async function refreshRelated() {
  const client = await pool.connect();
  try {
    await client.query("BEGIN");
    await client.query("DELETE FROM related_articles");
    const { rows } = await client.query("SELECT id FROM documents WHERE embedding IS NOT NULL");
    for (const { id } of rows) {
      await client.query(
        `INSERT INTO related_articles (article_id, rank, related_id, similarity)
         SELECT $1, row_number() OVER (ORDER BY similarity DESC), id, similarity
         FROM (${RELATED_SQL.replace(/;\s*$/, "")}) r`, [id]);
    }
    await client.query("COMMIT");          // readers see the old lists until here
  } catch (err) {
    await client.query("ROLLBACK");
    throw err;
  } finally {
    client.release();
  }
}

const app = express();
// Canner's scheduled job calls this; with a CRON_SECRET variable it sends the bearer itself
app.post("/jobs/refresh-related", (req, res) => {
  if (req.get("authorization") !== `Bearer ${process.env.CRON_SECRET}`) return res.sendStatus(403);
  res.sendStatus(202);                     // answer now, work after
  refreshRelated().catch((err) => console.error("refresh-related failed", err));
});
app.listen(process.env.PORT || 3000);

Reranking search results: what we tried

Reranking means taking the top few results from a fast search and reordering them with a slower, smarter model. Canner’s POST /v1/score returns how likely Granite finds each word of a text, optionally as the continuation of a context, for up to 32 texts in one request. We used it as a reranker: the question as context, each candidate article as a text to score, one request per search.

Raw likelihood mostly rewards short, predictable articles, so we also stored each article’s likelihood on its own and ranked by the gain the question gives it. That is the code below.

// rerank.js: what we tested. /v1/score isn't in the OpenAI SDK, so use its generic post().
import OpenAI from "openai";
import pg from "pg";

const ai = new OpenAI();
const db = new pg.Pool({ connectionString: process.env.DATABASE_URL, max: 2 });
const score = (body) => ai.post("/score", { body: { model: "granite-4.2-3b", ...body } });
// /v1/score takes at most 4,096 tokens per text (context included): keep the start of long articles.
const articleText = (d) => `${d.title}. ${d.body.slice(0, 6000)}`;

// Once per article (store it next to the embedding): how likely the text is on its own.
// ALTER TABLE documents ADD COLUMN score_baseline real;
export async function fillBaselines(rows) {          // up to 32 articles per call
  const r = await score({ context: "Help centre article:\n", input: rows.map(articleText) });
  for (const s of r.data) {
    await db.query("UPDATE documents SET score_baseline = $2 WHERE id = $1",
      [rows[s.index].id, s.total_logprob]);
  }
}

// Per search: how much more likely each candidate becomes after the question
export async function rerank(question, candidates) { // the top 8 from hybrid search
  const r = await score({
    context: `Customer question: ${question}\nHelp centre article that answers it:\n`,
    input: candidates.map(articleText),
  });
  return candidates
    .map((c, i) => ({ ...c, gain: r.data[i].total_logprob - c.score_baseline }))
    .sort((a, b) => b.gain - a.gain);
}

What reranking did: it made results worse

We wrote 16 harder questions whose answer is not the article sharing the most words (“the checkout page timed out”, “my card was issued in France”, “will someone phone me about my order”), took the top 8 from hybrid search (the right answer was among them every time), and compared orders.

  • The search was already right 15 times out of 16, so a reranker had one result to fix and fifteen to break. The gain-based reranker did fix the one miss (“will someone phone me about my order” → the fraud-check error page) and broke seven others.
  • It also added a second model call to every search, and that call waits its turn in the queue: our rerank requests took from a few seconds to over a minute while other work was queued. Each article’s baseline is one more call, once.
  • Scoring the other way round (how likely the question is, given each article) is a known reranking method, but it needs a separate request per candidate because the context changes each time. We didn’t test it: on a service that answers one request at a time it is too slow for a search box.
Order of the 8 candidatesRight article first (of 16)Right article in top 3
Vector order1516
Hybrid order1516
/v1/score: average word likelihood34
/v1/score: total likelihood27
/v1/score: gain over the article’s own likelihood913
Gain merged with the hybrid rank (RRF)1416

Running it on Canner

Related lists, similar items, duplicates and “because you read” are SQL over stored vectors: they run in your Dedicated Postgres instance in Montréal and use no AI model time. Only embedding new or edited content does, and that happens once per change in the background job. Text sent for embedding or scoring is processed in memory in Montréal and is not stored, not sent to another company and not used for training.

AI usage is measured in model time against a monthly allowance per plan: see AI endpoints for current allowances. Reranking with /v1/score adds a request per search, which is the main reason to measure before you turn it on.

Questions

How do I show related articles with pgvector?

Order the other rows by cosine distance to the current row’s embedding: ORDER BY embedding <=> (SELECT embedding FROM documents WHERE id = $1). Exclude the row itself, filter on language, skip near-duplicates, and precompute the lists if your pages are read often.

What cosine similarity means two items are duplicates?

It depends on the model and your content. With bge-m3 on our test set, a reworded duplicate scored 0.936 and the closest different article 0.869, so 0.90 worked. List your closest pairs, label them, and pick the cutoff between them.

Does reranking improve semantic search?

Not in our test. Reranking the top 8 hybrid results with /v1/score put the right article first 9 times out of 16, against 15 for plain vector order. Merged with the hybrid rank it reached 14. Measure on your own queries before you add it.

Do recommendations cost AI usage on every page view?

No. Related items and “because you read” are SQL queries over vectors already stored in Postgres. Only embedding new or changed content calls the model.

Can I run this on Canner’s shared Postgres?

No: pgvector needs the Dedicated Postgres add-on. Install it with canner db extensions <database> install vector.

Recommendations from your own data, in Montréal.

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