← All posts

Building with LLMs › RAG and vector search

What is semantic search? A plain guide to search by meaning

Semantic search ranks results by how close their meaning is to a query. How it differs from keyword search and BM25, and where hybrid search and rerankers fit.

If you’ve followed a tutorial for a chatbot that answers from your own documents, or read the introduction to a search engine or a vector database, you’ve probably come across the phrase semantic search. But what changes when search becomes “semantic,” and what it’s being compared with, often goes unexplained.

Semantic search is search that ranks documents by how close their meaning is to the query, rather than by whether they contain the same words. It turns the query and the documents into embeddings, lists of numbers that a model places close together when texts mean similar things, and returns the documents nearest to the query. The Sentence Transformers guide to semantic search also names handling synonyms, abbreviations, and misspellings as what sets it apart from keyword search. Perhaps the main reason you hear the term so often these days is LLM apps. A chatbot that answers from your documents first has to find the right passages, and people rarely ask with the exact words the documents use.

How keyword search finds documents

Let’s start with what semantic search is compared with. Keyword search, also called lexical search, starts from an inverted index. Like the index at the back of a book, it records, for each word, which documents contain it. The engine looks up each word of the query and scores only the documents on those lists. That’s why it’s fast, and also why a document that shares no words with the query never shows up at all.

A score grows the more often a word appears in a document, and the rarer that word is across the whole collection. Multiplying the two gives TF-IDF, short for term frequency times inverse document frequency. So a common word like “the” weighs little, while a rare word like an error code weighs a lot.

BM25 is a scoring function that refines this idea, and Robertson and Zaragoza’s 2009 review traces its roots to probabilistic retrieval research from the 1970s and 1980s. BM25 adds two adjustments. The first is saturation. However often a word repeats, its contribution can’t pass a certain limit, so a document that says “refund” twenty times doesn’t win by a factor of twenty, and k1 sets how quickly that limit is approached. The second is document length. A long document picks up more words just by being long, and b decides how much of that to discount. Elasticsearch, which uses BM25 by default, sets the defaults to k1 = 1.2 and b = 0.75.

Seven help articles and three questions

I made up seven short help articles for a note-taking app and ran both kinds of search over them. The part before the colon is the title, and four of them explain error codes.

docs = [
    "Refunds: open Orders, pick the purchase, and choose Request refund within 30 days.",
    "Plans: upgrade or downgrade your subscription in Billing settings.",
    "PAY-402: the bank declined your card. Try another card.",
    "SYNC-409: two devices edited the same note at once.",
    "SYNC-412: the app is out of date. Update it to keep syncing your notes.",
    "SYNC-429: too many sync requests in a short time. Wait a minute and try again.",
    "Two-factor login: signing in also needs a code from your phone.",
]
queries = ["how do I get my money back", "SYNC-412", "my card was rejected"]

Keyword search is BM25, written by hand. It builds the inverted index, then scores only the documents that share a word with the query.

import math, re
from collections import Counter

def tokenize(text):
    return re.findall(r"[a-z0-9]+(?:-[a-z0-9]+)*", text.lower())  # keeps sync-412 whole

counts = [Counter(tokenize(d)) for d in docs]
index = {}  # inverted index: term -> ids of docs containing it
for i, c in enumerate(counts):
    for term in c:
        index.setdefault(term, []).append(i)
avg_len = sum(sum(c.values()) for c in counts) / len(docs)

def bm25(query, k1=1.2, b=0.75):
    scores = Counter()
    for term in set(tokenize(query)):
        ids = index.get(term, [])
        idf = math.log(1 + (len(docs) - len(ids) + 0.5) / (len(ids) + 0.5))  # rare terms weigh more
        for i in ids:
            tf, length = counts[i][term], sum(counts[i].values())
            scores[i] += idf * tf / (tf + k1 * (1 - b + b * length / avg_len))
    return scores.most_common(3)

For semantic search I used all-MiniLM-L6-v2, a small public model that turns a sentence into 384 numbers, and measured closeness with cosine similarity, which is 1 when two vectors point the same way. With millions of documents, a vector database’s approximate nearest neighbor index would do this comparison quickly in its place.

from sentence_transformers import SentenceTransformer

model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
doc_vecs = model.encode(docs)

def embed_search(query):
    scores = model.similarity(model.encode(query), doc_vecs)[0]
    return [(int(i), float(scores[i])) for i in scores.argsort(descending=True)[:3]]

def show(hits, digits=3):
    return " | ".join(f"{docs[i].split(':')[0]} {s:.{digits}f}" for i, s in hits) or "(no match)"

for q in queries:
    print(q)
    print("  keyword  ", show(bm25(q)))
    print("  embedding", show(embed_search(q)))
how do I get my money back
  keyword   (no match)
  embedding Refunds 0.535 | PAY-402 0.412 | Plans 0.202
SYNC-412
  keyword   SYNC-412 0.697
  embedding SYNC-429 0.623 | SYNC-412 0.574 | SYNC-409 0.474
my card was rejected
  keyword   PAY-402 1.113
  embedding PAY-402 0.588 | Refunds 0.275 | Plans 0.250

The first question shares no words with any article, so keyword search found nothing, while semantic search put the refunds article first even though “money back” and “refund” are different words. The second question went the other way. Keyword search found the only article containing sync-412, and semantic search ranked SYNC-429 above it. Perhaps that’s because, to the model, two sync error codes in similar sentences look alike, and the code is only a small part of each sentence. The margin is thin, but this is exactly the kind of query where keyword search is steadier. For the third question, the word “card” and the meaning both pointed at PAY-402, so the two agreed.

Hybrid search, which combines the two

Since the two are strong in different places, it’s common to run both and merge the results, and this is called hybrid search. There are two ways to merge. To combine scores, you rescale values on different scales, like a BM25 score of 0.697 and a cosine similarity of 0.574, to between 0 and 1 and add them with weights. Otherwise, you combine ranks.

A common rank method is Reciprocal Rank Fusion (RRF), published by Cormack, Clarke, and Büttcher in 2009. For every list a document appears in, it adds 1/(k + rank), then sorts by the total. The paper fixed k at 60 and noted that the choice wasn’t critical. In its experiments, RRF did better than Condorcet Fuse, an established method, and in most cases better than the best single system too. Among products, Weaviate’s hybrid search offers both approaches.

def rrf(*rankings, k=60):
    fused = Counter()
    for hits in rankings:
        for rank, (i, _) in enumerate(hits, start=1):
            fused[i] += 1 / (k + rank)  # only the rank counts, not the score
    return fused.most_common(3)

for q in queries:
    print(f"{q:27}", show(rrf(bm25(q), embed_search(q)), digits=4))
how do I get my money back  Refunds 0.0164 | PAY-402 0.0161 | Plans 0.0159
SYNC-412                    SYNC-412 0.0325 | SYNC-429 0.0164 | SYNC-409 0.0159
my card was rejected        PAY-402 0.0328 | Refunds 0.0161 | Plans 0.0159

SYNC-412 was first in the keyword list and second in the embedding list, so it got 1/61 + 1/62, about 0.0325, while SYNC-429, which appeared only in the embedding list, stayed at 1/61. The first question simply kept the embedding order, so now the right article is first for all three questions.

Counting like this is also how search quality gets measured. Recall@k is the share of relevant documents that make it into the top k results, and since each question here has one right article, recall@1 is how often it came first. Keyword search and semantic search each got 2 out of 3, and RRF got all 3.

Reranking with a cross-encoder

A bi-encoder, which embeds the query and documents separately like the model above, is fast because documents can be embedded in advance, but it never reads the two side by side. A cross-encoder, on the other hand, takes the query and a document together as one input and outputs a single score. According to the Sentence Transformers Retrieve & Re-Rank guide, this is more accurate but too slow to score a huge number of pairs. That’s why you first narrow things down to around 100 candidates with keyword search or a bi-encoder, then reorder only those. I rescored the three articles semantic search had found with ms-marco-MiniLM-L6-v2, a model trained on MS MARCO passage ranking data.

from sentence_transformers import CrossEncoder

reranker = CrossEncoder("cross-encoder/ms-marco-MiniLM-L6-v2")
for q in queries:
    ids = [i for i, _ in embed_search(q)]  # the bi-encoder's top 3
    scores = reranker.predict([(q, docs[i]) for i in ids])  # reads query and doc together
    print(f"{q:27}", show(sorted(zip(ids, scores), key=lambda h: -h[1]), digits=2))
how do I get my money back  Refunds -7.12 | PAY-402 -10.21 | Plans -11.29
SYNC-412                    SYNC-412 7.60 | SYNC-429 1.77 | SYNC-409 1.36
my card was rejected        PAY-402 -0.35 | Refunds -11.05 | Plans -11.35

With the same three candidates, the cross-encoder put SYNC-412 first by a wide margin, perhaps because it reads the code in the query and the code in the article together. Unlike a similarity between 0 and 1, these are raw scores where higher means more relevant, and the model card’s example shows values like 8.6 and -4.3 too. So it’s best to compare them only among the candidates for one question.

Where it’s used, and where keywords still win

Semantic search is used in site search, in customer support that finds help articles or similar past inquiries, and in the retrieval step of RAG. One well-known example is Google. On October 25, 2019, Pandu Nayak wrote on Google’s blog that by using BERT, a neural network technique for understanding language, to rank results, Search would better understand one in 10 searches in the U.S. in English. In the post’s example, “2019 brazil traveler to usa need a visa,” the word “to” matters, and before, the results had been about U.S. citizens traveling to Brazil.

That doesn’t make keyword search outdated. In BEIR, a 2021 benchmark of 18 datasets, embedding-based retrievers did very well on some datasets but fell far behind BM25 on many others. The best approach was retrieving with BM25 and reranking with a cross-encoder, which beat BM25 on 16 of the 18 datasets but was much slower. Here are the differences we’ve seen so far.

Aspect Keyword search (BM25) Semantic search
What it compares Words shared with the query Closeness of meaning, via embeddings
Good at Error codes, names, rare words Paraphrased questions, synonyms
Weak at The same idea in different words Exact codes among similar documents
When nothing fits Returns nothing Still returns the nearest documents

So if people often search by part number or error code, it’s best to start with keyword search, and for a help center or RAG where everyone asks in their own words, start with semantic search. If you’re not sure which you have, hybrid search is probably a safe place to start.

Where to start

If you’re new to this, I’d suggest swapping the articles in the example for a dozen of your own documents, then writing down about twenty real questions with the right document for each and comparing recall@5 for the three approaches. If you already run an engine like Elasticsearch, where BM25 is already working, adding vector search and RRF on top of it is a natural next step. I ran the examples on October 28, 2026 on an Apple M4 Mac with Python 3.13.12, sentence-transformers 6.2.0, transformers 5.20.2, and PyTorch 2.14.1. Running them on the CPU printed the same numbers.

AI tools helped with the research for this post.