Skip to content

Vector Search vs. Keyword Search: Testing How AI Retrieval Systems Find Content

Keyword blocks and a network of vector points flowing into one funnel, illustrating vector vs keyword search

The vector vs keyword search debate matters for AEO because AI retrieval systems use both. Keyword search matches the exact words in a query. Vector search matches meaning, even when the words differ. Many production systems run both and merge the results, a method called hybrid search.

This guide explains how each approach works, from TF-IDF and BM25 to embeddings and Reciprocal Rank Fusion. It then compares all three on the same corpus with standard evaluation metrics. The full Python code is included, so you can reproduce the test with your own content.

How does traditional keyword retrieval work?

Short answer: Keyword retrieval builds an inverted index that lists which documents contain each word. At query time, it finds documents that share words with the query and scores them by how important and frequent those words are.

It is fast, transparent and very good at exact matches, such as product names, error codes and model numbers. Its weakness is vocabulary mismatch. A query for “outsourced monitoring” will not match a page that only says “managed detection and response”.

What are TF-IDF and BM25?

Short answer: TF-IDF scores a word higher when it appears often in a document but rarely across the corpus. BM25 refines that idea by capping the effect of repeated words and adjusting for document length.

BM25 is still the default keyword algorithm in many search engines, including the full-text side of hybrid systems such as Azure AI Search. Its two settings, k1 and b, control how fast repeated words stop adding score and how much long documents are penalized.

How do embedding models create vector representations?

Short answer: An embedding model turns text into a list of numbers, called a vector, so that texts with similar meaning end up close together. Queries and documents are embedded the same way, so they can be compared directly.

Modern embedding models learn from huge amounts of text, so “laptop” and “endpoint device” can land near each other. This is what lets vector search handle synonyms and paraphrases that keyword search misses.

How does cosine similarity explain vector vs keyword search?

Short answer: Cosine similarity measures the angle between two vectors. A score near 1 means the texts point in the same direction in meaning; a score near 0 means they are unrelated.

Semantic relevance is not the same as topical overlap. Two passages can share many words and differ in meaning, or share few words and mean the same thing. That gap is the heart of the vector vs keyword search question.

How does Approximate Nearest Neighbor (ANN) search work?

Short answer: Comparing a query with millions of vectors one by one is too slow. ANN indexes, such as HNSW graphs, find vectors that are very likely the closest ones, trading a little accuracy for large speed gains.

For a small experiment, exact comparison is fine. At production scale, ANN settings affect recall, so retrieval quality depends partly on index tuning, not just on the embedding model.

How does hybrid search settle vector vs keyword search?

Short answer: Hybrid search runs keyword and vector retrieval in parallel, then merges the two ranked lists. Reciprocal Rank Fusion (RRF) does the merge by giving each document 1 divided by (k plus its rank) in each list, then summing.

RRF ignores raw scores, which are not comparable across methods, and uses only positions. Microsoft’s hybrid ranking documentation notes that k works best at a small value such as 60. A document ranked high in either list gets a strong boost, and one found by both methods rises further.

Where does semantic reranking fit?

Short answer: A reranker takes the top results from retrieval and scores each one against the query with a more expensive model. It reorders a short list rather than searching the whole corpus.

Rerankers often fix the order of results that retrieval found but ranked poorly. They cannot fix results that retrieval never found. That is why recall at the first stage, often improved by hybrid search, still matters.

How do you compare vector vs keyword search on the same dataset?

Short answer: Use one corpus, one set of test queries and graded relevance labels. Run BM25, vector search and hybrid RRF, then compare Precision@K, Recall@K, MRR and nDCG@K.

The script below runs the full experiment. Its default embedding uses LSA, a classic method that runs offline. For a realistic test, swap in a modern sentence-embedding model, as shown in the comments.

#!/usr/bin/env python3
"""Compare keyword (BM25), vector and hybrid (RRF) retrieval on the same corpus.

Metrics: Precision@K, Recall@K, MRR and nDCG@K, using graded relevance labels.

Install: pip install scikit-learn numpy
Usage:   python retrieval_compare.py corpus.json qrels.json
corpus.json: [{"id": "d1", "text": "..."}]
qrels.json:  [{"q": "query text", "rel": {"d1": 3, "d4": 1}}]   (3 = highly relevant)

The default embed() uses LSA (TF-IDF + SVD) so it runs offline. For a real test,
replace it with a sentence-embedding model, for example:
    from sentence_transformers import SentenceTransformer
    model = SentenceTransformer("all-MiniLM-L6-v2")
    def embed(texts): return model.encode(texts, normalize_embeddings=True)
"""
import json
import math
import re
import sys
from collections import Counter

import numpy as np
from sklearn.decomposition import TruncatedSVD
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import Normalizer

K = 3
STOP = set("a an and are as at be by can do does for from how i in is it of on or our the to "
           "what when where which with you your".split())


def tokens(text):
    return [t for t in re.findall(r"[a-z0-9]+", text.lower()) if t not in STOP]


# ---------- keyword retrieval: BM25 ----------
def bm25_ranking(docs, query, k1=1.5, b=0.75):
    toks = [tokens(d) for d in docs]
    avgdl = sum(map(len, toks)) / len(toks)
    df = Counter(t for d in toks for t in set(d))
    scores = []
    for i, d in enumerate(toks):
        tf = Counter(d)
        s = sum(
            math.log(1 + (len(toks) - df[t] + 0.5) / (df[t] + 0.5))
            * tf[t] * (k1 + 1) / (tf[t] + k1 * (1 - b + b * len(d) / avgdl))
            for t in tokens(query) if t in tf
        )
        scores.append(s)
    return list(np.argsort(scores)[::-1])


# ---------- vector retrieval ----------
def build_embedder(docs, dims=8):
    lsa = make_pipeline(TfidfVectorizer(stop_words="english", sublinear_tf=True),
                        TruncatedSVD(n_components=dims, random_state=42), Normalizer())
    lsa.fit(docs)
    return lsa.transform


def vector_ranking(doc_vecs, query_vec):
    sims = doc_vecs @ query_vec.T  # cosine similarity on normalized vectors
    return list(np.argsort(sims.ravel())[::-1])


# ---------- hybrid retrieval: Reciprocal Rank Fusion ----------
def rrf(rankings, k=60):
    scores = Counter()
    for ranking in rankings:
        for pos, doc in enumerate(ranking, start=1):
            scores[doc] += 1 / (k + pos)
    return [doc for doc, _ in scores.most_common()]


# ---------- metrics ----------
def metrics(ranking, ids, rel, k=K):
    top = [ids[i] for i in ranking[:k]]
    hits = [d for d in top if rel.get(d, 0) > 0]
    precision = len(hits) / k
    recall = len(hits) / len([d for d, g in rel.items() if g > 0])
    first = next((pos + 1 for pos, i in enumerate(ranking) if rel.get(ids[i], 0) > 0), None)
    mrr = 1 / first if first else 0
    dcg = sum((2 ** rel.get(d, 0) - 1) / math.log2(pos + 2) for pos, d in enumerate(top))
    ideal = sorted(rel.values(), reverse=True)[:k]
    idcg = sum((2 ** g - 1) / math.log2(pos + 2) for pos, g in enumerate(ideal))
    return np.array([precision, recall, mrr, dcg / idcg if idcg else 0])


def main(corpus_path, qrels_path):
    corpus = json.load(open(corpus_path, encoding="utf-8"))
    qrels = json.load(open(qrels_path, encoding="utf-8"))
    ids, docs = [d["id"] for d in corpus], [d["text"] for d in corpus]
    embed = build_embedder(docs)
    doc_vecs = embed(docs)

    totals = {"BM25 (keyword)": 0, "Vector": 0, "Hybrid (RRF)": 0}
    print(f"Top-{K} results per query")
    for item in qrels:
        kw = bm25_ranking(docs, item["q"])
        vec = vector_ranking(doc_vecs, embed([item["q"]]))
        hyb = rrf([kw, vec])
        print(f"\n  {item['q']}")
        for name, ranking in (("BM25 (keyword)", kw), ("Vector", vec), ("Hybrid (RRF)", hyb)):
            totals[name] = totals[name] + metrics(ranking, ids, item["rel"])
            print(f"    {name:<16}{', '.join(ids[i] for i in ranking[:K])}")

    print(f"\n{'Method':<16}{'P@'+str(K):>8}{'R@'+str(K):>8}{'MRR':>8}{'nDCG@'+str(K):>9}")
    for name, total in totals.items():
        p, r, m, n = total / len(qrels)
        print(f"{name:<16}{p:>8.2f}{r:>8.2f}{m:>8.2f}{n:>9.2f}")


if __name__ == "__main__":
    main(sys.argv[1], sys.argv[2])

Our test corpus had twelve short documents about security products and eight queries, including “What is the best cybersecurity solution for an enterprise?”. Each query had graded labels from 1 to 3. Results at K = 3:

Method               P@3     R@3     MRR   nDCG@3
BM25 (keyword)      0.46    0.79    0.92     0.86
Vector              0.46    0.79    0.88     0.82
Hybrid (RRF)        0.46    0.79    0.94     0.87

Hybrid search scored highest on MRR and nDCG, but the gaps were small. The more useful finding was a shared failure. For “outsourced security monitoring around the clock”, no method retrieved the managed detection and response page. That page says “24/7 team of analysts”, with no shared words. The offline LSA model also missed it. Closing that kind of vocabulary gap is exactly what a modern embedding model is built for.

What does vector vs keyword search mean for AEO content strategies?

Short answer: Write so both methods can find you. Use the exact terms buyers search for, so keyword retrieval matches. Explain the same idea in plain, related language, so vector retrieval matches too.

  • Name your category the way buyers do, not only in internal jargon.
  • Include common synonyms near key terms, such as “managed detection and response (outsourced 24/7 monitoring)”.
  • Keep product names, model numbers and integrations in visible text for exact matching.
  • Write one clear passage per question, as covered in our guide to chunking for AI search.

What are the limits of experimental retrieval environments?

Short answer: A small local corpus cannot reproduce commercial AI search, which uses proprietary models, huge indexes, rerankers and trust signals. Use experiments to understand mechanisms, not to predict rankings.

Our dataset is tiny, the labels are our own and the default embedding is a simple offline model. Results will shift with a different corpus or model. For how retrieval fits into the full answer pipeline, see our guide to RAG in AI search.

Frequently asked questions about vector vs keyword search

Is vector search better than keyword search?

Not in every case. Vector search handles synonyms better, while keyword search wins on exact names and codes. Hybrid search usually combines the strengths of both.

Do AI answer engines use hybrid search?

Many retrieval platforms support hybrid search, but AI answer engines rarely publish their exact methods. Assume both exact terms and meaning can matter.

What does k = 60 mean in RRF?

It is a smoothing constant. It reduces the gap between top-ranked documents, so no single list dominates the fused result.

Which metric should I use to compare retrieval methods?

Use MRR when one right answer matters most, and nDCG when results have graded relevance. Precision and recall at K help explain the differences.

Can I run this vector vs keyword search test without paid APIs?

Yes. The script runs offline with scikit-learn. Open-source embedding models can also run locally for a more realistic test.

Next step

Collect 20 real buyer questions, label which of your pages answer each one and run the script. Pages that only one method finds usually need clearer wording or missing synonyms.

Want more practical guides on vector vs keyword search? Browse the latest articles on the Blippu blog.

See all articles