Semantic Search Implementation — AI Web

Semantic search searches by meaning, not by identical words. Each synopsis is embedded once and stored with bookId and embeddedAt (when the vector was made)…

A Bookshop customer types "a story from colonial times" into the search box. Those words aren't in any book's title, yet This Earth of Mankind and Beauty Is a Wound should still be found, because both synopses tell of colonial times. A search that can find those two books is called semantic search: it searches by meaning, not by identical letters.

But searching by meaning alone isn't enough. Imagine the shop has two assistants. The first only reads the labels on the spines: he quickly finds "Pramoedya" (the author of This Earth of Mankind), but is lost when asked for "a story of pupils on an island". The second has read every synopsis, so she understands what you mean, but sometimes forgets names. A good shop sends both to look and then merges their answers. That's hybrid search. In this picture, the first assistant is keyword search (a search for identical words), and the second is semantic search.

Two stages: index once, search many times

The Embedding and RAG lessons introduced the two moments below. In a search box, both become code that runs all the time:

  1. Index time: each synopsis is embedded once, then stored as one row: bookId, vector, and embeddedAt (when that vector was made).
  2. Query time: on every search, the customer's text is embedded with the same model, compared with every vector, and the top results are taken.

Here is the index-time function on the Bookshop server:

// Index time: once per book, and again when its synopsis changes
async function indexBooks(books) {
  const res = await client.embeddings.create({
    model: "text-embedding-3-small",
    input: books.map((b) => b.synopsis), // many synopses in 1 request
  });
  return books.map((b, i) => ({
    bookId: b.id,
    vector: res.data[i].embedding, // 1,536 numbers, length 1
    embeddedAt: new Date().toISOString(),
  }));
}

The Lab's toy embedding: concept counting

A model's vectors can't be calculated on paper, and the Lab doesn't call a model. In the Embedding lesson we used a word-counting toy embedding. That toy embedding failed on "a story of pupils on an island", because it doesn't know that "pupils" and "school" are related. Here we add one step: words with related meanings are counted in the same dimension (one number in the vector). The dictionary is small, 8 concepts, written by hand. It is not a model: a real model learns by itself which words are close, from huge amounts of text, with 1,536 dimensions.

The eight concepts: education (school, pupils, pupil, students, teacher, primary, hbs, study), village/island (belitung, island, hamlet, village), family (families, family, children, descendants, daughter), colonial (colonial, dutch), politics (political, politics, 1965, upheaval), dance (ronggeng, dancer, dance, traditional), love, and poor. For example, The Rainbow Troops synopsis has three education words: "primary", "school" and "teacher". Here is the result for each synopsis (only the synopsis is embedded, not the title or the author):

Book Concept vector Length
The Rainbow Troops education 3, family 2, village/island 1, poor 1 √15 = 3.873
This Earth of Mankind education 2, family 1, colonial 1, love 1 √7 = 2.646
Beauty Is a Wound family 1, colonial 2, politics 1 √6 = 2.449
The Dancer dance 3, politics 3, village/island 1 √19 = 4.359

Searching: embed the question, cosine, top-k, threshold

The question "a novel about a school on Belitung" becomes the vector education 1 and village/island 1, with length √2 = 1.414. Here is its cosine similarity with each book (the dot product divided by the product of the two lengths, from the Embedding lesson):

Book Dot product Cosine Threshold 0.30 Threshold 0.60
The Rainbow Troops 3 + 1 = 4 4 / (1.414 × 3.873) = 0.730 shown shown
This Earth of Mankind 2 2 / (1.414 × 2.646) = 0.535 shown dropped
The Dancer 1 1 / (1.414 × 4.359) = 0.162 dropped dropped
Beauty Is a Wound 0 0 dropped dropped

Top-k means taking the k best results (here k = 2). The threshold is the minimum score a result needs to be shown. Without one, with k = 3, The Dancer is shown for a question about a school, just because of the word "hamlet". The right threshold depends on the model, so measure it on your own data (see the section Measuring quality).

Here is the query-time code. Each question's vector is kept in a cache (a store of results you already asked for), then compared with every vector in the index:

const cache = new Map(); // question text -> vector

async function embedQuestion(text) {
  const key = text.trim().toLowerCase().replace(/\s+/g, " ");
  if (cache.has(key)) return cache.get(key); // cache hit: no request
  const res = await client.embeddings.create({ model: "text-embedding-3-small", input: key });
  cache.set(key, res.data[0].embedding);
  return res.data[0].embedding;
}

async function searchVector(text, index, threshold = 0.3, k = 2) {
  const q = await embedQuestion(text);
  return index
    .map((row) => ({ bookId: row.bookId, score: dot(q, row.vector) })) // length 1: dot = cosine
    .filter((h) => h.score >= threshold)
    .sort((a, b) => b.score - a.score)
    .slice(0, k);
}

Keyword search: BM25

Keyword search matches identical words in the title, author and synopsis. The most common way to score it is called BM25, with three rules:

The full formula, with k1 = 1.2 and b = 0.75 (the usual defaults), is in the Lab's code. In Postgres this job is done by the built-in full-text search (to_tsvector, ts_rank_cd). Its scoring formula isn't exactly BM25, but its job is the same: matching words.

Before you look at the table, guess: a customer types "a story of pupils on an island". Which book does keyword search put first: The Rainbow Troops, or another one?

Here are the keyword search results for three questions, compared with the concept vectors. The keyword scores use the English titles. The Lab shows the Indonesian titles, so its keyword scores differ a little:

Question Keyword (BM25) Vector (concepts, threshold 0.30)
a novel about a school on Belitung The Rainbow Troops 1.965, This Earth of Mankind 0.628 ("school") The Rainbow Troops 0.730, This Earth of Mankind 0.535
a story of pupils on an island Beauty Is a Wound 1.222 The Rainbow Troops 0.730, This Earth of Mankind 0.535
Pramoedya This Earth of Mankind 1.091 (empty)

For "a story of pupils on an island", keyword search puts Beauty Is a Wound first, only because its synopsis starts with "The story of". "Pupils" and "island" aren't in any synopsis. Vector search finds The Rainbow Troops, because "pupils" and "school" sit in the same concept.

So the difference: keyword search matches words literally (letter for letter), while semantic search understands meaning and context. But keyword search wins for names, codes and numbers that must match exactly. "Pramoedya" is found through keywords, while its concept vector is empty, because a person's name is in no concept.

Hybrid search: reciprocal rank fusion

Hybrid search runs keyword search and vector search, then merges the results. Their scores can't simply be added, because they are on different scales: a BM25 score can be more than 1 (for example 1.222), while a cosine is at most 1 (for example 0.730). So what gets merged is the rank, the position of a book in each list. The method is called reciprocal rank fusion (RRF): each book gets 1 / (60 + rank) from each list it appears in, and those values are added up. 60 is the usual constant. pgvector's hybrid search example (pgvector is a Postgres extension that stores and searches vectors) uses 60 too.

"a story of pupils on an island" Keyword rank Vector rank RRF
The Rainbow Troops (none) 1 1/61 = 0.0164
Beauty Is a Wound 1 (none) 1/61 = 0.0164
This Earth of Mankind (none) 2 1/62 = 0.0161

The Rainbow Troops and Beauty Is a Wound tie, and the tie is broken by book id: the smaller id comes first. With top-2, the right book, The Rainbow Troops, is still shown even though keyword search got it wrong. For "a story from colonial times", Beauty Is a Wound is rank 1 in both lists (1/61 + 1/61 = 0.0328), and This Earth of Mankind is rank 2 in both (1/62 + 1/62 = 0.0323). A book that appears in both lists gets two shares, so it moves up.

Here is the RRF function. i + 1 is the rank, because i is 0 for the first book in a list:

const K_RRF = 60;

function rrf(keywordList, vectorList) {
  const score = new Map();
  for (const list of [keywordList, vectorList]) {
    list.forEach((h, i) => score.set(h.bookId, (score.get(h.bookId) ?? 0) + 1 / (K_RRF + i + 1)));
  }
  return [...score]
    .map(([bookId, s]) => ({ bookId, score: s }))
    .sort((a, b) => b.score - a.score || a.bookId - b.bookId); // tie: smaller id first
}

Re-indexing and caching questions

The admin edits The Rainbow Troops synopsis on 11 October 2026 at 09:15: "Mrs. Mus" becomes "Mrs. Muslimah". Its vector was made on 1 October, so it is now stale: it still stands for the old text. The keyword index in Postgres (for example a generated tsvector column, which is calculated automatically from other columns) changes in the same UPDATE command. A vector is different: it needs a request to OpenAI, so the book has to be embedded again. This code picks the books that need it:

// Runs after PUT /books/{id}, or every night
const stale = books.filter((b) => {
  const row = index.find((r) => r.bookId === b.id);
  return !row || new Date(b.updatedAt).getTime() > new Date(row.embeddedAt).getTime(); // never indexed, or the synopsis is newer
});
const fresh = stale.length ? await indexBooks(stale) : [];
index = [...index.filter((r) => !stale.some((b) => b.id === r.bookId)), ...fresh];

Both times, updatedAt (when the synopsis changed) and embeddedAt, are first turned into milliseconds with new Date(...).getTime(). The reason: the Postgres driver pg (a Node.js library for Postgres) returns a timestamp column such as updatedAt as a Date object, while embeddedAt is ISO text. The comparison Date > text is always false, so without this step no book is ever embedded again. With this step, the result is 1 book embedded again and 3 skipped. The last line replaces that book's old index row with the new one. Comparing updatedAt with embeddedAt is cheaper and safer than embedding every book again whenever something changes.

A question cache saves requests for repeated questions. The question "a novel about a school on Belitung" is only 8 tokens. For 10,000 searches a day, that is 10,000 × 8 tokens = 80,000 tokens = $0.0016. So the main gain of the cache isn't money but waiting time (one HTTP request fewer) and rate limits (the limit on how many requests the provider accepts). If you switch embedding models, empty the cache and re-index every book.

Measuring quality: precision@k and recall

Don't judge a search by one or two tries. Build a labelled set: a list of questions, each with the books that really are relevant. Then compute:

The Lab's labelled set has six questions, each with its relevant books:

An example for one question: at threshold 0.30, vector search shows The Rainbow Troops and This Earth of Mankind for the school question. Only The Rainbow Troops is relevant, so precision is 1/2 = 0.5 and recall 1/1 = 1. Here is the average over all six questions, with k = 2:

Method Threshold 0.30: precision / recall Threshold 0.60: precision / recall
Keyword (BM25) 0.750 / 0.833 0.750 / 0.833
Vector (concepts) 0.667 / 0.833 0.833 / 0.667
Hybrid (RRF) 0.833 / 1.000 0.833 / 1.000

Raising the threshold to 0.60 drops This Earth of Mankind (0.535) from the school question, so the precision of vector search goes up. But This Earth of Mankind (0.378) also disappears from "a story from colonial times", so its recall goes down. Choosing a threshold is always a trade between these two numbers. Hybrid is the only one that finds every relevant book, because keywords cover the gaps of vector search and the other way round. Its precision stays at 0.833 here, because the keyword side also brings This Earth of Mankind for "school". Six questions is very few. In a real shop, take tens to hundreds of real questions from the search log (the record of every customer search).

⚠️ Results that don't fit and stale vectors

TL;DR: Semantic search searches by meaning, not by identical words. Each synopsis is embedded once and stored with bookId and embeddedAt (when the vector was made). On every search, the question is embedded with the same model, and its vector is kept in a cache so the same question isn't sent again. Results are ranked by cosine (the dot product for OpenAI's vectors), those under the threshold (the minimum score) are dropped, and the top k are taken. Keyword search, scored with BM25, matches words literally and wins for names and codes. Semantic search understands meaning. Hybrid search merges both rankings with RRF (reciprocal rank fusion): each book gets 1 / (60 + rank) from each list, added up. When updatedAt (when the synopsis changed) is newer than embeddedAt, embed that book again and only that one. Measure quality on a labelled set (questions with the books that are relevant to each): precision@k (what share of the results is relevant) and recall (what share of the relevant books was found). In the Lab, hybrid finds every relevant book at both thresholds.

⚡ Searching meaning, not letters

Meaning: Semantic search searches by meaning, not by identical letters. Each book's synopsis is embedded once and stored with bookId and embeddedAt (when the vector was made). On every search, the question is embedded with the same model. Books are ranked from the highest cosine similarity, books scoring under the threshold (the minimum score) are dropped, and the top k (the k best results) are taken.

⚡ Keyword against vector

Guess first: keyword search matches identical words. A customer types "a story of pupils on an island". The words "pupils" and "island" are in no synopsis, but "story" is in the synopsis of Beauty Is a Wound. Which book does keyword search put first: The Rainbow Troops (pupils on Belitung) or Beauty Is a Wound?

Beauty Is a Wound, only because its synopsis starts with "The story of". Vector search finds The Rainbow Troops, because "pupils" and "school" (in The Rainbow Troops synopsis) are close in meaning, so their vectors are similar.

Meaning: Keyword search matches words literally, semantic search understands meaning and context. But for names and codes, such as the author's name "Pramoedya", keyword search wins.

⚡ Hybrid: merge the rankings

Write:

const K_RRF = 60;

function rrf(keywordList, vectorList) {
  const score = new Map();
  for (const list of [keywordList, vectorList]) {
    list.forEach((h, i) => score.set(h.bookId, (score.get(h.bookId) ?? 0) + 1 / (K_RRF + i + 1)));
  }
  return [...score]
    .map(([bookId, s]) => ({ bookId, score: s }))
    .sort((a, b) => b.score - a.score || a.bookId - b.bookId); // tie: smaller id first
}

Meaning: Hybrid search runs keyword search and vector search, then merges the two result lists. Keyword search scores (BM25) and cosine scores are on different scales, so what gets merged is the rank. The method is called RRF (reciprocal rank fusion): each book gets 1 / (60 + rank) from each list it appears in, and those are added up. i + 1 is the rank, because i is 0 for the first book in a list. A book that appears in both lists gets two shares, so it moves up.

⚡ Measure, don't judge by feel

Meaning: Build a labelled set: a list of questions, each with the books that really are relevant. Precision@k: of the results shown (at most k), what share is relevant. Recall: of all the relevant books, what share was found. A higher threshold raises precision but can lower recall.

What you will learn