Zero Labs
Industry News / AI

Custom Reranking in RAG: How to Combine Semantic and Keyword Scores for Better Relevance

Source · Towards AI By Aayush Gupta

From the publisher’s feed, collected in the ZeroLabs newsroom.

This is Part 3 of a 5-part series on building a production-grade RAG system.Part 1 — Hybrid RAG OverviewPart 2 — Semantic Chunking vs Fixed ChunkingPart 3 — Custom Reranking (you are here)Part 4 — Parent-Child Document ArchitecturePart 5 — Building a Tool-Augmented RAG AgentPinecone’s hybrid search returns results sorted by a blended vector score using the alpha parameter. It's a reasonable first pass. But it's done inside the database, which means it uses the raw dot product between query and document vectors — not a normalized similarity you can reason about or tune.What if you want to weight the dense and sparse components differently after retrieval? What if you want full score transparency for debugging? This article walks through a custom reranking function built on top of Pinecone’s retrieval results — taking the top-K candidates and re-scoring them with explicit cosine similarity math, using the same 768-dim vectors produced by Ollama’s nomic-embed-text.Why Rerank After Retrieval?Pinecone’s alpha blends vectors at the query stage before results are returned. The problem is that dot product scores aren't normalized — a chunk with a large magnitude vector will score higher regardless of true similarity. More importantly, you have no visibility into how much each component contributed to the final ranking.Custom reranking gives you three things:Transparency — you can log dense, sparse, and hybrid scores separatelyControl — you can tune the weight between semantic and keyword relevance per use casePortability — the logic is decoupled from the database and works with any embedding modelThe Reranking FunctionThe full reranker takes the query’s dense embedding, the query’s sparse vector, and the retrieved chunks with their stored values:def rerank_chunks(query_embedding, sparse_vector_object, retrieved_chunks): """ Rerank retrieved chunks using hybrid similarity scoring. Combines dense (semantic) and sparse (keyword) similarities. """ sparse_query_dict = dict(zip( sparse_vector_object["indices"], sparse_vector_object["values"] )) for chunk in retrieved_chunks: chunk_embedding = chunk["values"] sparse_dict = dict(zip( chunk["sparse_values"]["indices"], chunk["sparse_values"]["values"] )) # Sparse similarity: cosine over shared token indices common = set(sparse_query_dict.keys()) & set(sparse_dict.keys()) dot = sum(sparse_query_dict[k] * sparse_dict[k] for k in common) norm1 = math.sqrt(sum(v ** 2 for v in sparse_query_dict.values())) norm2 = math.sqrt(sum(v ** 2 for v in sparse_dict.values())) sparse_sim = dot / (norm1 * norm2) if norm1 and norm2 else 0 # Dense similarity: cosine over 768-dim Ollama embedding vectors dense_sim = cosine_similarity([query_embedding], [chunk_embedding])[0][0] # Weighted combination hybrid_sim = 0.4 * dense_sim + 0.6 * sparse_sim chunk["metadata"]["similarity"] = hybrid_sim retrieved_chunks.sort(key=lambda x: x["metadata"]["similarity"], reverse=True) return [chunk["metadata"] for chunk in retrieved_chunks]Let’s break down the three computations.Dense Similaritydense_sim = cosine_similarity([query_embedding], [chunk_embedding])[0][0]This is standard cosine similarity between the 768-dimensional Ollama nomic-embed-text query embedding and the stored chunk embedding. The value ranges from -1 to 1, though in practice it stays positive for document-query pairs.The embeddings come from the same local model used at indexing time, so this comparison is valid. The client is initialized with Ollama’s local server as covered in Part 1 — no round trips to an external API during reranking.Sparse SimilaritySPLADE vectors are sparse: most dimensions are zero, and only a handful of token-level features are active. Rather than loading them into a full numpy array and computing cosine similarity (wasteful at 30,000+ vocabulary dimensions), the reranker works directly with the sparse representation:# Convert to dicts for fast intersection lookupsparse_query_dict = dict(zip(sparse_vector_object["indices"], sparse_vector_object["values"]))sparse_dict = dict(zip(chunk["sparse_values"]["indices"], chunk["sparse_values"]["values"]))# Only sum over dimensions both vectors sharecommon = set(sparse_query_dict.keys()) & set(sparse_dict.keys())dot = sum(sparse_query_dict[k] * sparse_dict[k] for k in common)norm1 = math.sqrt(sum(v ** 2 for v in sparse_query_dict.values()))norm2 = math.sqrt(sum(v ** 2 for v in sparse_dict.values()))sparse_sim = dot / (norm1 * norm2) if norm1 and norm2 else 0This is the cosine similarity formula applied to sparse vectors. The common set intersection means you only iterate over overlapping token features — much cheaper than iterating the full vocabulary space.The Hybrid Formulahybrid_sim = 0.4 * dense_sim + 0.6 * sparse_simThe 60/40 split favoring sparse (keyword) signals is intentional for this domain. Recipe retrieval benefits heavily from exact ingredient and dish names — “lentil dal” or “nomic-embed-text” should score high because those tokens appear verbatim. Semantic similarity alone would score a “chickpea curry” chunk nearly as high as “lentil dal” for a lentil dal query, because they’re both Indian lentil dishes.You can invert this weighting for more abstract knowledge bases where concepts matter more than exact terms. With Ollama’s nomic-embed-text, which is optimized for retrieval tasks, you may find that equal weighting (0.5 / 0.5) works well for general corpora.Real Output: What Reranking Actually DoesHere is the full score breakdown for the query "How to make veggie burgers?":Chunk doc19_p0_c0: Dense=0.442, Sparse=0.460, Hybrid=0.453Chunk doc19_p1_c0: Dense=0.440, Sparse=0.346, Hybrid=0.383Chunk doc19_p2_c0: Dense=0.355, Sparse=0.344, Hybrid=0.348Chunk doc19_p3_c0: Dense=0.462, Sparse=0.310, Hybrid=0.371Chunk doc16_p1_c0: Dense=0.337, Sparse=0.142, Hybrid=0.220Chunk doc17_p1_c0: Dense=0.356, Sparse=0.136, Hybrid=0.224Chunk doc17_p0_c0: Dense=0.203, Sparse=0.170, Hybrid=0.183After reranking:1. veggie_burgers.txt — Hybrid: 0.45282. veggie_burgers.txt — Hybrid: 0.38353. veggie_burgers.txt — Hybrid: 0.37104. veggie_burgers.txt — Hybrid: 0.34825. vegetable_stir_fry — Hybrid: 0.22446. vegetable_paella.txt — Hybrid: 0.2200The top 4 results are all from the correct source document. Notice that doc16_p1_c0 (vegetable paella) has a respectable dense score of 0.337 — semantically similar to a veggie burger recipe — but its sparse score is only 0.142 because it shares very few keyword tokens with "veggie burgers." The hybrid formula correctly pushes it down.For a harder query — "lentil dal tomato" — the sparse signal becomes even more decisive:Chunk doc6_p0_c0: Dense=0.529, Sparse=0.419, Hybrid=0.463 ← lentil_dal.txtChunk doc6_p1_c0: Dense=0.513, Sparse=0.378, Hybrid=0.432 ← lentil_dal.txtChunk doc5_p1_c0: Dense=0.306, Sparse=0.221, Hybrid=0.255 ← chickpea_curry.txtThe lentil dal document dominates on both axes. The agent’s final answer (“Yes. Lentil dal calls for 3 tomatoes, chopped”) is grounded in exactly this chunk.The Complete Search and Rerank PipelineThe search_and_rerank function ties retrieval and reranking together:async def search_and_rerank(query, top_k=10, alpha=0.6): """Complete search and rerank pipeline.""" print(f"Searching for: '{query}'") # Dense query embedding via Ollama query_embedding = await get_embeddings([query]) query_vector = query_embedding[0]["embedding"].vector # Sparse query vector via SPLADE sparse_values = splade.encode_documents([query])[0] # Pinecone hybrid retrieval results = index.query( namespace=index_name, top_k=top_k, include_metadata=True, include_values=True, vector=query_vector, sparse_vector=sparse_values, alpha=alpha ) # Re-score and sort reranked = rerank_chunks(query_vector, sparse_values, results.matches.copy()) return results.matches, rerankedNote that results.matches.copy() is passed to the reranker — the original Pinecone ordering is preserved separately so you can compare original vs. reranked results if needed.Tuning the WeightsThe 0.4 / 0.6 split is a starting point. To tune it systematically, you'd want a labeled evaluation set: a collection of queries and their known correct documents. Then you can grid-search:for dense_w in [0.3, 0.4, 0.5, 0.6, 0.7]: sparse_w = 1.0 - dense_w scores = evaluate(queries, labels, dense_w, sparse_w) print(f"Dense: {dense_w}, Sparse: {sparse_w}, MRR: {scores['mrr']:.3f}")Because both the embedding and inference steps run locally via Ollama, you can run evaluation loops like this without incurring API costs — useful when iterating on weight tuning.For general knowledge bases, 0.5 / 0.5 is a reasonable default. For highly specific technical or product documentation, skewing toward sparse (0.3 / 0.7) typically improves precision.What’s NextPart 4 — Parent-Child Architecture: The reranked child chunks point to parent chunks with richer context. How does that look in practice?Part 5 — The Agent Layer: How search_and_rerank is registered as a typed tool and called by an agent mid-conversation.Part 2 — Semantic Chunking: How the chunks being reranked here were created in the first place.Custom Reranking in RAG: How to Combine Semantic and Keyword Scores for Better Relevance was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.