Dense, Sparse, Hybrid Retrieval, Reranking and RAG

Article · 6:00

Where dense retrieval fails, sparse and BM25-style retrieval, hybrid search and score fusion, reranking with a cross-encoder, RAG integration, and upsert freshness.

This lesson has 1 runnable example. Press Try yourself! under any of them to open it in the editor.

Dense retrieval fails in specific, predictable ways, and knowing them is what makes hybrid search a decision rather than a fashion.

An embedding captures meaning and loses precision. So dense retrieval is excellent at "how do I get my money back" matching a document titled "Refund policy", and poor at exact matches: a product code (SKU-4471-B), a person's name, an error code (ORA-01555), a version number, or a rare technical term the model never saw in training. The embedding for SKU-4471-B is close to the embedding for SKU-4471-C, which is exactly wrong.

Sparse retrieval is the complement. A sparse vector has one dimension per vocabulary term and is mostly zeros - it is lexical matching, essentially BM25, expressed as a vector. It excels at exact terms and rare words and is blind to meaning: "cheap" does not match "inexpensive".

Hybrid search runs both and fuses the scores, which is why it usually beats either. Pinecone supports sparse-dense vectors in a single index with an alpha weighting, and the alternative - two queries fused in the application - gives you more control. The fusion methods: weighted score combination (simple, and needs the score scales to be comparable) and reciprocal rank fusion, which combines by rank rather than score and is more robust precisely because it does not care about scale.

The honest finding, which the laboratory establishes: hybrid wins on mixed corpora with both conceptual and exact-match queries, and does not always beat dense alone on purely conceptual ones. So measure it per query type rather than enabling it globally. Splitting your ground truth into conceptual and exact-match questions and reporting both is the measurement that makes the decision.

Reranking is the biggest single quality improvement after chunking. A cross-encoder reads the query and a candidate document together and scores their relevance - far more accurate than comparing two independently-computed embeddings, and far too slow to run over a whole corpus. The pattern: retrieve the top 50 to 100 with the vector search, rerank them with the cross-encoder, return the top 5. The cost is latency - typically tens to hundreds of milliseconds for 50 candidates - and the benefit is routinely a large jump in precision at small k.

RAG integration - retrieval-augmented generation - is where most of this ends up: retrieve relevant chunks, put them in a language model's prompt, generate an answer grounded in them. The retrieval-side concerns that matter: how many chunks to include (a context budget in tokens); deduplicating chunks from the same document; including the source id so the answer can be cited, which is a product requirement and not a nicety; and a relevance threshold below which you return "I do not know" rather than retrieving something irrelevant and letting the model confabulate around it.

Freshness and consistency. Pinecone's upserts are eventually consistent: a vector you just wrote may not appear in a query immediately, typically within seconds. There is no read-your-writes mechanism. So a workflow that ingests a document and immediately searches for it may not find it, and the answers are to tolerate it, to poll, or to serve the newly-ingested item from somewhere else until it lands.

Laboratory exercise 3 - a retrieval service, measured.

Build a question-answering retrieval service and run at least 100 concurrent clients.

Split your ground truth into conceptual questions and exact-match questions - product codes, error codes, names. This split is what makes the rest of the laboratory meaningful.

Measure four retrieval configurations against both halves: dense only, sparse only, hybrid with three alpha values, and hybrid with reciprocal rank fusion. Produce a table of recall@5 and MRR for each configuration on each half. The expected finding is that the winner differs by question type, and demonstrating that is the point.

Add a cross-encoder reranker over the top 50 and re-measure all configurations, recording the latency it added and the precision it bought.

Build the RAG pipeline with a context budget, deduplication, source citation and a relevance threshold. Demonstrate the threshold working: ask a question your corpus cannot answer and show the service declining rather than confabulating.

Measure the freshness gap: upsert a vector and query for it in a tight loop, recording how long until it appears. Do this at idle and under ingestion load.

Deliverable: the service, the ground-truth split, the four-configuration table on both halves, the reranker's latency and precision effect, the RAG pipeline with the threshold demonstrated, the freshness measurement at idle and under load, and a recommendation for which configuration to ship and why.

PY Example 1 190 lines
# ==================================================================
# *** WHERE DENSE RETRIEVAL FAILS. Predictably. ***
# ==================================================================
# An embedding captures MEANING and loses PRECISION. So dense is:
#
#   EXCELLENT at   "how do I get my money back" -> "Refund policy"
#   POOR at        exact matches:
#                    a product code   SKU-4471-B
#                    a person's name  "Ada Lovelace"
#                    an error code    ORA-01555
#                    a version        "v2.14.3"
#                    a rare term the model never saw in training
#
# *** THE EMBEDDING FOR SKU-4471-B IS CLOSE TO THE EMBEDDING FOR
# *** SKU-4471-C, WHICH IS EXACTLY WRONG. *** Demonstrate it: query
# for an exact code and look at what comes back.

# ==================================================================
# SPARSE is the complement: lexical matching, as a vector.
# ==================================================================
from pinecone_text.sparse import BM25Encoder

bm25 = BM25Encoder()
bm25.fit([c["text"] for c in all_chunks])      # fit on YOUR corpus
bm25.dump("bm25_params.json")                  # and VERSION IT -
                                               # refitting changes
                                               # every sparse vector

sv = bm25.encode_queries("SKU-4471-B refund eligibility")
#   {'indices': [18402, 91, 4420, ...], 'values': [0.81, 0.22, ...]}
#   One dimension per vocabulary term, MOSTLY ZEROS.
#   Excellent at exact terms and rare words. BLIND TO MEANING:
#   "cheap" does not match "inexpensive".

# ==================================================================
# HYBRID: run both, FUSE the scores.
# ==================================================================
# Pinecone supports sparse-dense in one index with an ALPHA weight:
def weight_by_alpha(dense, sparse, alpha):
    # alpha = 1.0 -> pure dense;  0.0 -> pure sparse
    assert 0 <= alpha <= 1
    return ([v * alpha for v in dense],
            {"indices": sparse["indices"],
             "values": [v * (1 - alpha) for v in sparse["values"]]})

d, s = weight_by_alpha(
    model.encode(q, normalize_embeddings=True).tolist(),
    bm25.encode_queries(q), alpha=0.7)
res = index.query(vector=d, sparse_vector=s, top_k=50,
                  namespace=ns, include_metadata=True)

# OR two queries fused in the application, which gives MORE CONTROL:
def reciprocal_rank_fusion(*ranked_lists, k=60):
    # *** COMBINES BY RANK, NOT SCORE - which makes it ROBUST
    # *** PRECISELY BECAUSE IT DOES NOT CARE ABOUT SCALE. ***
    # Weighted score fusion needs the two score scales to be
    # comparable, and dense cosine scores and BM25 scores are not.
    scores = {}
    for lst in ranked_lists:
        for rank, m in enumerate(lst, start=1):
            scores[m["id"]] = scores.get(m["id"], 0.0) + 1.0 / (k + rank)
    return sorted(scores.items(), key=lambda kv: kv[1], reverse=True)

dense_hits  = index.query(vector=dv, top_k=50, namespace=ns,
                          include_metadata=True)["matches"]
sparse_hits = index.query(sparse_vector=sv, top_k=50, namespace=ns,
                          include_metadata=True)["matches"]
fused = reciprocal_rank_fusion(dense_hits, sparse_hits)

# ==================================================================
# *** THE HONEST FINDING - and it is why you SPLIT THE GROUND TRUTH. ***
# ==================================================================
#   configuration         CONCEPTUAL        EXACT-MATCH
#                         recall@5  MRR     recall@5  MRR
#   dense only              0.91    0.78      0.41    0.29
#   sparse only             0.52    0.37      0.94    0.88
#   hybrid alpha=0.9        0.91    0.77      0.58    0.44
#   hybrid alpha=0.7        0.89    0.75      0.81    0.71
#   hybrid alpha=0.5        0.84    0.70      0.90    0.84
#   RRF (dense + sparse)    0.90    0.76      0.92    0.86
#
# *** THE WINNER DIFFERS BY QUESTION TYPE. *** Hybrid wins on a
# MIXED corpus and does NOT always beat dense alone on a purely
# conceptual one. So MEASURE IT PER QUERY TYPE rather than enabling
# it globally - and RRF is usually the safe default because it is
# the least sensitive to the mix.
#
# Splitting the ground truth into conceptual and exact-match halves
# is what makes this table possible, and it takes ten minutes.

# ==================================================================
# *** RERANKING: the biggest quality gain after chunking. ***
# ==================================================================
from sentence_transformers import CrossEncoder
reranker = CrossEncoder("cross-encoder/ms-marco-MiniLM-L-6-v2")

def retrieve_and_rerank(q, namespace, candidates=50, final=5):
    qv = model.encode(q, normalize_embeddings=True).tolist()
    hits = index.query(vector=qv, top_k=candidates, namespace=namespace,
                       include_metadata=True)["matches"]
    # *** A CROSS-ENCODER READS THE QUERY AND THE DOCUMENT TOGETHER ***
    # - far more accurate than comparing two independently-computed
    # embeddings, and FAR TOO SLOW to run over a whole corpus. Hence
    # the pattern: retrieve 50 cheaply, rerank them expensively.
    pairs = [(q, h["metadata"]["excerpt"]) for h in hits]
    scores = reranker.predict(pairs)
    for h, s in zip(hits, scores):
        h["rerank_score"] = float(s)
    hits.sort(key=lambda h: h["rerank_score"], reverse=True)
    return hits[:final]

#   dense top-5                      recall@5 0.91  MRR 0.78   12 ms
#   dense top-50 + rerank to 5       recall@5 0.96  MRR 0.91  128 ms
#                                                              ^^^^
#   *** THE COST IS LATENCY (tens to hundreds of ms for 50
#   *** candidates). THE BENEFIT IS A LARGE JUMP IN PRECISION AT
#   *** SMALL k. *** Measure both and decide; for a
#   question-answering service the trade is usually worth it.

# ==================================================================
# RAG: the retrieval-side concerns that actually matter.
# ==================================================================
CONTEXT_BUDGET_TOKENS = 3000
RELEVANCE_THRESHOLD = 0.35          # TUNE THIS from your ground
                                    # truth - it is not a constant

def build_context(q, namespace):
    hits = retrieve_and_rerank(q, namespace, candidates=50, final=10)

    # *** A RELEVANCE THRESHOLD, so the service says "I do not know"
    # *** rather than retrieving something irrelevant and letting the
    # *** model confabulate around it. *** This is the difference
    # between a useful system and a confident liar.
    hits = [h for h in hits if h["rerank_score"] >= RELEVANCE_THRESHOLD]
    if not hits:
        return None, []

    # DEDUPLICATE by document: five chunks of one page crowd out the
    # other sources and make the answer narrower than the corpus.
    seen, chosen, tokens = set(), [], 0
    for h in hits:
        doc = h["metadata"]["doc_id"]
        if doc in seen: continue
        text = h["metadata"]["excerpt"]
        n = len(text.split()) * 4 // 3        # a rough token estimate
        if tokens + n > CONTEXT_BUDGET_TOKENS: break
        seen.add(doc); chosen.append(h); tokens += n

    # *** INCLUDE THE SOURCE ID SO THE ANSWER CAN BE CITED. *** A
    # product requirement, not a nicety: an uncitable answer cannot
    # be checked, and a RAG system nobody can check is not
    # trustworthy.
    context = "\n\n".join(
        f"[{h['metadata']['doc_id']}] {h['metadata']['title']}\n"
        f"{h['metadata']['excerpt']}"
        for h in chosen)
    return context, [h["metadata"]["doc_id"] for h in chosen]

# DEMONSTRATE THE THRESHOLD: ask something your corpus cannot
# answer and show the service DECLINING. That demonstration is worth
# more than any relevance number.

# ==================================================================
# *** FRESHNESS: UPSERTS ARE EVENTUALLY CONSISTENT. ***
# ==================================================================
import time
index.upsert(vectors=[{"id": "probe", "values": qv,
                       "metadata": {"probe": True}}], namespace=ns)

t0 = time.perf_counter()
while True:
    r = index.query(vector=qv, top_k=1, namespace=ns,
                    filter={"probe": {"$eq": True}})
    if r["matches"]: break
    time.sleep(0.05)
print("visible after", time.perf_counter() - t0, "s")

# *** A VECTOR YOU JUST WROTE MAY NOT APPEAR IMMEDIATELY ***, and
# there is NO READ-YOUR-WRITES mechanism - no bookmark, no
# consistency flag.
#
# SO a workflow that ingests a document and immediately searches for
# it MAY NOT FIND IT. The three answers:
#   1. TOLERATE IT, having measured the gap
#   2. POLL, as above, where the workflow allows
#   3. SERVE THE NEW ITEM FROM ELSEWHERE until it lands - the
#      system that owns the documents already has it
#
# MEASURE IT AT IDLE AND UNDER INGESTION LOAD. Under load it is
# longer, which is exactly when a user will notice.

Open this example in the editor and change it. Nothing you type is saved.

Discussion

No questions on this topic yet. Sign in to ask the first one.