Stage 1 of the RAG funnel: why you need both vector search (ANN) and BM25

Stage 1 of the RAG funnel: why you need both vector search (ANN) and BM25

Part 3 of 7 in the RAG in Production series: engineer-level, on Azure, mapped to Microsoft exam AI-103.

TL;DR for managers. Vector search understands meaning: "annual leave" matches "holiday". Keyword search (BM25) matches exact words: error codes, part numbers, names, exam codes. Each misses things the other finds, so production RAG runs both at once. This is called hybrid search, and in Azure it is one request.

Stage 1 has one job: make sure the right chunk is somewhere in the candidate list. It is judged on recall, not on ordering. Two very different retrievers do that job better together than either does alone.

What vectors miss

An embedding model turns a chunk into, say, 1,536 numbers that capture its meaning. Similar meanings land close together, which is why vector search handles paraphrases well. It is weaker on:

  • Exact identifiers. "AZ-104", "0x80070005", "INV-2026-0042". To an embedding model these are a few tokens with little meaning, and "AZ-104" lands near "AZ-900".
  • Rare and new terms. Product names and acronyms that weren't common in the embedding model's training data.
  • Short chunks dominated by one word and long chunks where the relevant sentence is a small part of the whole.

What BM25 misses, and how it scores

BM25 (Robertson and Zaragoza, 2009) ranks a chunk by how often the query words appear in it, weighted by how rare each word is across the whole index, and normalised for chunk length:

score(D, Q) = Σ over query terms q of
              IDF(q) × f(q, D) × (k1 + 1) / ( f(q, D) + k1 × (1 − b + b × |D| / avgdl) )

f(q, D) is how many times the term appears in the chunk, |D| is the chunk length, avgdl the average length. k1 (default 1.2 in Azure) caps how much repeating a word helps, and b (default 0.75) controls the length penalty. The IDF part is why a rare word like "0x80070005" carries the whole score. BM25 has no idea that "holiday" and "annual leave" mean the same thing, unless you add a synonym map.

Which one wins? Three queries

Query Vector (ANN) BM25 Why
"How much annual leave do new starters get?" Finds "holiday entitlement" chunk Misses it if the policy only says "holiday" Paraphrase: meaning beats words
"Error 0x80070005 when installing Teams" Returns general installation-troubleshooting chunks Finds the chunk containing the exact code Rare exact token with high IDF
"Is AZ-104 still a current exam?" Mixes AZ-104, AZ-900 and AZ-305 chunks Pins AZ-104 chunks Identifier, not meaning

Hybrid search doesn't need to know in advance which kind of query it is getting. Both legs run, and stage 2 merges them.

ANN: why not just compare every vector?

Exact nearest-neighbour search compares the query with every vector: 100,000 chunks of 1,536 dimensions is about 154 million multiply-adds per query. That's fine. At 100 million chunks it's 154 billion per query, which is not. Approximate nearest neighbour (ANN) algorithms answer "which vectors are probably closest?" while looking at a tiny fraction of the index.

Azure AI Search uses HNSW, Hierarchical Navigable Small World graphs (Malkov and Yashunin, 2016). A road-map analogy works well: the top layers are motorways with few, long links; lower layers are A-roads; the bottom layer is every street. A search starts at the top, moves greedily towards the query, then drops a layer and repeats with finer links.

The three HNSW parameters in Azure

Parameter Default (range) What it does Turn it up when
m 4 (4 to 10) Links per node in the graph Recall is low on a large, varied index. Costs memory.
efConstruction 400 (100 to 1,000) Candidates considered while building the graph You can afford slower indexing for a better graph
efSearch 500 (100 to 1,000) Candidates considered per query Recall is low. Costs query latency.

An index built for hybrid search

Note the separate codes field with the keyword analyser: identifiers like "AZ-104" are kept whole instead of being split at the hyphen. The groups field holds the Entra ID groups allowed to see each chunk, for security trimming.

{
  "name": "expenses",
  "fields": [
    { "name": "chunk_id", "type": "Edm.String", "key": true, "filterable": true },
    { "name": "title",    "type": "Edm.String", "searchable": true, "analyzer": "en.microsoft" },
    { "name": "content",  "type": "Edm.String", "searchable": true, "analyzer": "en.microsoft" },
    { "name": "codes",    "type": "Collection(Edm.String)", "searchable": true, "analyzer": "keyword",
      "filterable": true },
    { "name": "groups",   "type": "Collection(Edm.String)", "filterable": true, "retrievable": false },
    { "name": "content_vector", "type": "Collection(Edm.Single)", "searchable": true,
      "dimensions": 1536, "vectorSearchProfile": "hnsw-profile" }
  ],
  "vectorSearch": {
    "algorithms": [ { "name": "hnsw-1", "kind": "hnsw",
      "hnswParameters": { "m": 4, "efConstruction": 400, "efSearch": 500, "metric": "cosine" } } ],
    "vectorizers": [ { "name": "aoai", "kind": "azureOpenAI",
      "azureOpenAIParameters": { "resourceUri": "https://<aoai>.openai.azure.com",
        "deploymentId": "text-embedding-3-small", "modelName": "text-embedding-3-small" } } ],
    "profiles": [ { "name": "hnsw-profile", "algorithm": "hnsw-1", "vectorizer": "aoai" } ]
  }
}

Measure your ANN recall

This is the step most teams skip. Azure lets you run the same vector query with exhaustive set to true, which does a brute-force search over the whole index. That gives you the true nearest neighbours to compare HNSW against. Microsoft's docs suggest exactly this use for exhaustive KNN.

from azure.search.documents.models import VectorizableTextQuery

def top_ids(query: str, exhaustive: bool, k: int = 50) -> list[str]:
    vq = VectorizableTextQuery(text=query, k_nearest_neighbors=k,
                               fields="content_vector", exhaustive=exhaustive)
    return [r["chunk_id"] for r in search.search(search_text=None, vector_queries=[vq],
                                                 top=k, select=["chunk_id"])]

def ann_recall(queries: list[str], k: int = 50) -> float:
    """Share of the true k nearest neighbours that HNSW also returned."""
    scores = []
    for q in queries:
        exact = set(top_ids(q, exhaustive=True, k=k))    # brute force: the ground truth
        approx = set(top_ids(q, exhaustive=False, k=k))  # HNSW
        scores.append(len(exact & approx) / len(exact))
    return sum(scores) / len(scores)

print(f"ANN recall@50: {ann_recall(sample_queries):.3f}")

If ANN recall is well below what you need, raise efSearch first (query-time only, no rebuild), then consider m. Keep in mind that this measures HNSW against exact vector search. It says nothing about whether the vectors themselves find the right chunks. That's part 7.

Filters: before or after?

If a user may only see chunks for their groups, the filter must be applied before the ANN search. Otherwise HNSW finds 50 neighbours, the filter removes 45, and you re-rank 5. Azure's preFilter mode does this:

results = search.search(
    search_text=question,
    vector_queries=[VectorizableTextQuery(text=question, k_nearest_neighbors=50, fields="content_vector")],
    filter="groups/any(g: search.in(g, 'all-staff,finance-team', ','))",   # security trimming
    vector_filter_mode="preFilter",                                         # filter before the ANN search
    top=50)

Learning this for AI-103? Microsoft's AI-103 exam (Azure AI Apps and Agents Developer Associate) asks you to implement RAG, configure semantic, hybrid and vector search for grounding, and monitor relevance and grounding quality. Our live online AI-103 course builds these pipelines hands-on in Microsoft Foundry and Azure AI Search, on UK time, with mock assessments before you book the exam.

The RAG in Production series

  1. Part 1: RAG or fine-tuning?
  2. Part 2: The RAG retrieval funnel
  3. Part 3: Stage 1: ANN + BM25 hybrid search (you are here)
  4. Part 4: Stage 2: Reciprocal Rank Fusion
  5. Part 5: Stage 3: re-ranking with cross-encoders
  6. Part 6: Scaling: 10,000 vs 10 million documents
  7. Part 7: Evaluating RAG: retrieval vs generation
Back to blog

Ready to take the first step?

Live online courses on UK time, mapped to the current Microsoft AI exams. No coding needed for AI at work.

Explore AI coursesAsk us a question