Opening: a myth that slows you down
Many teams start a retrieval‑augmented generation (RAG) effort believing that a single vector store can answer any enterprise question. The reality is that most corporate knowledge bases contain a mix of dense semantic content and precise keyword‑driven artifacts such as policy IDs, contract numbers, or SKU codes. Treating everything as a plain embedding leads to missed matches, higher latency, and a higher chance of hallucinated answers.
In this note I walk through a pattern that couples a vector index with a traditional inverted index, picks the right store for each, and adds cheap caching layers so the system stays responsive even when traffic spikes.
Why the hybrid approach matters now
Enterprises are adding large language models to internal tools faster than ever. The promise is that a single prompt can surface information from PDFs, wikis, ticketing systems, and relational databases. Yet the cost of a naïve full‑text scan grows linearly with document size, and pure vector search struggles with exact identifiers. Combining the two retrieval modalities lets you keep latency in the low‑hundreds of milliseconds while preserving the ability to retrieve exact matches.
At the same time, the market offers both open‑source vector engines (for example, FAISS, Milvus, or Qdrant) and managed services (such as Pinecone or Azure Vector Search). Each brings different operational trade‑offs around scaling, security, and pricing. Understanding those trade‑offs early helps you avoid a costly re‑architecture later.
Technical deep dive
The core of a hybrid RAG pipeline looks like this:
- Ingest documents, split them into chunks, and create two parallel indices: a dense vector index for semantic similarity and an inverted index for keyword matching.
- When a query arrives, run it through a lightweight keyword parser (often just a Boolean match) and a dense encoder (like OpenAI’s text‑embedding‑ada‑002).
- Merge the two result sets using a simple scoring rule, then feed the top‑k passages to the LLM.
- Cache the merged result for identical queries to avoid repeating the two searches.
Below is a minimal Python example that demonstrates the split‑search‑merge flow using sentence‑transformers for embeddings and whoosh for the keyword index. The code is deliberately simple; production code would add async I/O, retries, and observability hooks.
import os
from sentence_transformers import SentenceTransformer
from whoosh import index
from whoosh.fields import Schema, TEXT, ID
import numpy as np
import faiss
# 1. Load encoder
embedder = SentenceTransformer('all‑mpnet‑base‑v2')
# 2. Build keyword index (whoosh)
schema = Schema(doc_id=ID(stored=True), content=TEXT(stored=True))
if not os.path.exists('kw_idx'):
os.mkdir('kw_idx')
kw_ix = index.create_in('kw_idx', schema)
writer = kw_ix.writer()
# Assume docs is a list of (id, text)
for doc_id, text in docs:
writer.add_document(doc_id=str(doc_id), content=text)
writer.commit()
# 3. Build vector index (FAISS)
vectors = []
ids = []
for doc_id, text in docs:
vec = embedder.encode(text, convert_to_numpy=True)
vectors.append(vec)
ids.append(int(doc_id))
vectors_np = np.vstack(vectors).astype('float32')
dim = vectors_np.shape[1]
faiss_index = faiss.IndexFlatL2(dim)
faiss_index.add(vectors_np)
def hybrid_search(query, top_k=5):
# keyword part
with kw_ix.searcher() as searcher:
kw_results = searcher.search(kw_ix.query_parser.parse(query), limit=top_k)
kw_ids = {int(r['doc_id']) for r in kw_results}
# dense part
q_vec = embedder.encode(query, convert_to_numpy=True).astype('float32')
_, vec_ids = faiss_index.search(q_vec.reshape(1, -1), top_k)
vec_ids = set(vec_ids[0].tolist())
# simple merge: union with a bias toward keyword hits
merged = list(kw_ids.union(vec_ids))
return merged[:top_k]
Trade‑offs in this snippet are explicit. Whoosh gives you fast Boolean matching but no scaling beyond a single node; FAISS is memory‑heavy but gives sub‑millisecond similarity search on a single machine. If you need horizontal scaling, replace FAISS with Milvus or a managed service, and replace Whoosh with Elasticsearch or OpenSearch.
Common pitfalls and failure modes
- Over‑relying on embeddings for numeric identifiers. Vector similarity treats “order‑12345” as a semantic token, which often yields unrelated matches. Always keep a keyword path for exact fields.
- Ignoring index freshness. Enterprises update policies daily. If the vector store is only refreshed nightly, the LLM will answer with stale snippets, leading to drift between the model’s knowledge and the source.
- Cache stampede. When a hot query misses the cache, many parallel requests can trigger duplicate heavy searches, saturating the vector engine. A simple lock or token bucket around the cache‑miss path prevents this.
- Silent hallucinations. The LLM may fabricate details if the retrieved context is too short or irrelevant. Without a relevance score check, you can’t tell when the model is guessing.
Practical implementation guide
Follow these steps to build a production‑grade hybrid RAG pipeline:
- Choose the right stores. For small to medium corpora (< 1 million chunks), an open‑source combination of Qdrant (or Milvus) and Elasticsearch works well and keeps costs low. For larger scale or strict SLAs, consider a managed vector service with built‑in replication and a hosted search engine for keywords.
- Define a chunking strategy. Split PDFs at logical headings, keep tables as separate chunks, and preserve identifiers as standalone snippets. Store the chunk ID in both indices.
- Implement a dual ingest pipeline. As each chunk is generated, send the raw text to the keyword index and the embedding to the vector store. Use a message queue (Kafka or RabbitMQ) to decouple the two paths and guarantee eventual consistency.
- Add a lightweight cache. Redis with a TTL of 5‑10 minutes works for most query patterns. Cache the merged list of passage IDs and, optionally, the rendered LLM prompt.
- Score and filter before prompting. Compute a combined relevance score:
score = 0.7 * keyword_match + 0.3 * vector_score. Drop any passage below a threshold (e.g., 0.4) to reduce hallucination risk. - Monitor key metrics. Track latency of each search leg, cache hit ratio, and the proportion of LLM responses that trigger a post‑hoc fact‑check (you can run a simple regex or a secondary retrieval pass). Alert when latency exceeds 300 ms or when hallucination‑rate spikes above 5 %.
- Plan for drift. Schedule incremental re‑embedding of updated documents and run a nightly diff against the previous vector set. Flag chunks whose embedding distance exceeds a set delta; those likely need manual review.
Final thoughts
Hybrid retrieval is not a silver bullet, but it gives you a pragmatic path to high‑quality answers without blowing up latency budgets. The biggest wins come from treating the vector store and keyword engine as complementary, not competing, services. Keep an eye on cache health, refresh your embeddings regularly, and build a cheap sanity‑check layer that can catch obvious hallucinations before they reach the user.
When you balance open‑source flexibility with the reliability of managed services, you also keep the door open for future upgrades—whether that means moving to a newer embedding model or scaling the keyword side to a multi‑region search cluster.
Take the next step
Ready to try this pattern in your own environment? Visit akkistech.com for a starter kit, sample Docker compose files, and a community forum where you can share results and ask questions.