Knowledge / Artificial Intelligence and Data Science / Retrieval-augmented generation and vector databases

Retrieval-augmented generation and vector databases

Artificial Intelligence and Data Science (B.E./B.Tech) · AI applications · free study notes for exams, placements and interviews

In short

Retrieval-augmented generation (RAG) puts a search step in front of a language model: the user's question is used to fetch relevant passages from a private corpus, and those passages are pasted into the prompt so the model answers from evidence instead of from memory alone. A vector database is the store that makes this fetch fast — it keeps embedding vectors plus their text and metadata, and answers approximate nearest-neighbour (ANN) queries in milliseconds over millions of vectors. RAG is the standard industrial fix for three LLM weaknesses: stale knowledge, hallucination and no access to internal data, and it avoids the cost of fine-tuning. In Indian university syllabi it appears in AI-applications, information-retrieval and generative-AI electives; in placement rounds (TCS, Infosys, Wipro, HCLTech, Accenture, Zoho, Freshworks, Sarvam AI, Krutrim, Yellow.ai) a RAG pipeline is the single most common "build this" question for an AI/DS fresher.

Explained

Why RAG, and where it sits

The indexing (offline) pipeline

  1. Ingest — PDFs, DOCX, HTML, tickets, Confluence, SQL rows; OCR scanned Indian government PDFs; keep tables as Markdown, not flattened text.
  2. Clean and segment — strip headers/footers, keep headings as structure signals.
  3. Chunk — split into retrievable units. Strategies: fixed-size by tokens; recursive character splitting (paragraph → sentence → word); semantic chunking (break where consecutive sentence embeddings diverge); layout/heading-aware for structured manuals; parent–child (embed small child chunks, return the larger parent for context).
  4. Overlap — repeat 10–20% of tokens between chunks so a sentence split across a boundary is still findable.
  5. Embed — one dense vector per chunk from an embedding model (dimensions typically 384–3,072). Chunks must be embedded with the *same* model and the same instruction prefix as the queries.
  6. Store — vector + chunk text + metadata (doc id, title, page, date, department, language, access tags).
  7. Build the index — HNSW/IVF structure; optionally a parallel BM25/keyword index for hybrid search.
  8. Re-indexing: incremental upsert by document id; deletes must remove the vector *and* its text, else deleted data keeps surfacing.

The query (online) pipeline

  1. Query processing — rewrite a follow-up into a standalone question using chat history ("and his salary?" → "What is the salary of a Grade-4 operator?"); optional multi-query expansion and HyDE (embed a hypothetical answer instead of the question).
  2. Retrieve — top-k by vector similarity (k typically 20–50 as a candidate pool), with metadata filtering (date range, department, user's access role) applied pre- or post-filter.
  3. Hybrid search — combine dense (semantic) with sparse BM25 or SPLADE (lexical, good for product codes, IS numbers, section numbers, names) and fuse with reciprocal rank fusion (RRF) or weighted scores.
  4. Rerank — a cross-encoder reranker scores each (query, chunk) pair jointly; far more accurate than the bi-encoder embedding, far slower, so it is run only on the candidate pool, cutting 50 → 5.
  5. Assemble the prompt — system instruction + numbered passages with source labels + question; respect the context budget; put the most relevant passage first or last (models attend least to the middle — the "lost in the middle" effect).
  6. Generate with citations — require passage numbers in the answer so a reviewer can verify.
  7. Post-check — optional groundedness/NLI check that each sentence is entailed by a cited passage; refuse or escalate otherwise.
  8. Agentic / iterative RAG — the model decides whether to retrieve, issues several searches, and retries on a failed answer (self-RAG, corrective RAG).
  9. GraphRAG — build an entity–relation graph over the corpus; answers "how are X and Y connected" and multi-hop questions that chunk retrieval misses.

Vector databases: what they are and how they index

Evaluation and tuning

Advantages, limitations and Indian compliance

Key points

Formulas and examples

cos(q, d) = (q · d) / (‖q‖ ‖d‖) — q, d are embedding vectors (dimensionless); value in [−1, 1], 1 = same direction
For unit vectors: ‖q − d‖² = 2 − 2 cos(q, d) — L2 distance from cosine
Chunks per document = ceil((T − C) / (C − O)) + 1 — T = doc tokens, C = chunk tokens, O = overlap tokens
Index size (float32) ≈ N × d × 4 bytes; HNSW graph adds ≈ N × M × 2 × 4 bytes (layer 0 ≈ 2M links)
PQ bytes per vector = m (sub-vectors) × bits/8; compression = 4d / (m × bits/8)
recall@k = (relevant chunks in top k) / (total relevant); precision@k = (relevant in top k) / k
MRR = (1/Q) Σ 1/rank of first relevant result; a query with none scores 0
DCG@k = Σᵢ relᵢ / log₂(i + 1); nDCG@k = DCG@k / IDCG@k
RRF score(d) = Σ over retrievers 1/(k + rankᵢ(d)), k = 60 by convention
Prompt tokens ≈ system + question + (k × chunk tokens); cost = tokens × price per token

Example 1 — chunk count, index size, compression. 5,000 documents, 4,000 tokens each; C = 512, O = 64.

Example 2 — cosine similarity by hand. q = [0.2, 0.5, 0.1], d = [0.1, 0.4, 0.3].

Example 3 — IVF speed-up. N = 45,000, nlist = 256 → ≈ 176 vectors per cell. With nprobe = 8, vectors scanned = 8 × 176 = 1,408 = 3.1% of the index, i.e. ≈ 32× fewer distance computations than flat search (45,000 / 1,408 = 31.96). Raising nprobe to 32 scans 12.5% and lifts recall, at 4× the latency.

Example 4 — retrieval metrics. A query has 4 relevant chunks; the top 10 contain 3 of them, at ranks 1, 2 and 5.

Example 5 — context budget and monthly cost (illustrative prices; vendor rates change). 500 queries/day, k = 5 chunks of 512 tokens, system prompt 400 + question 60 tokens, output 300 tokens. Assume ₹0.25 per 1,000 input tokens and ₹1.00 per 1,000 output tokens.

RRF fusion check. Doc A: dense rank 2, BM25 rank 8 → 1/62 + 1/68 = 0.01613 + 0.01471 = 0.03084. Doc B: dense rank 1, BM25 rank 50 → 1/61 + 1/110 = 0.01639 + 0.00909 = 0.02548. A outranks B despite losing on dense alone — agreement across retrievers wins.

ApproachKnowledge freshnessCost to updateCitationsBest for
Prompt stuffingInstantNoneYesA few pages
RAGRe-index a documentLow (minutes)YesChanging facts, private corpora
Fine-tuningRetrainHighNoStyle, format, narrow tasks
Long-context, no retrievalInstantNoneWeakSingle large document
IndexBuildQueryRAMRecallUse when
Flat (exact)NoneO(N·d)Vectors only100%N ≲ 1 lakh
IVF-Flatk-means trainnprobe/nlist of NVectors + centroidsTunable highMillions, RAM available
IVF-PQ / DiskANNTrain + encodeFastVery lowModerate–high10⁸+ vectors, SSD
HNSWSlow, memory-heavyFastest at high recallHighHighest per msLow-latency production
# minimal RAG loop (pseudocode)
chunks = split(docs, size=512, overlap=64)
store.upsert([(embed(c.text), c.text, c.meta) for c in chunks])

def answer(q, history):
    q2 = rewrite(q, history)
    dense  = store.search(embed(q2), k=50, filter={"dept": user.dept})
    sparse = bm25.search(q2, k=50)
    pool   = rrf(dense, sparse, k=60)
    top    = cross_encoder.rerank(q2, pool)[:5]
    prompt = SYSTEM + format_with_sources(top) + q2   # "answer only from these; else say unknown"
    return llm(prompt)

Where it is used

Interview questions

Common mistakes

Related topics

Text embeddings and semantic search · Large language models and prompt engineering · AI agents and tool use · Natural language processing basics · Information retrieval and ranking · Knowledge graphs and GraphRAG

Open in the Knowledge reader →Find jobs →