RAG, embeddings and vector databases

Part 4: RAG and Vector DBs

Chunking, vector search, hybrid search, reranking, RAG evaluation.

Live · updated 26 Nov 2026, 5:11 pm~17 min read
On this page (29 sections)

Like I'm 5: An open-book exam. Before answering, the student finds the right pages in the textbook, then writes the answer using them. RAG gives the model a textbook.

4.1 RAG foundations

Topics to cover, in this order:

  1. Why RAG (vs fine-tuning vs long context)
  2. The RAG pipeline end to end
  3. Embeddings deep dive and similarity (cosine, dot product, Euclidean)
  4. Vector databases: Pinecone, Weaviate, Qdrant, Chroma, pgvector, FAISS, Milvus
  5. Indexing: HNSW, IVF and approximate nearest neighbour

4.2 Preparing and retrieving data

Topics to cover, in this order:

  1. Chunking strategies (size, overlap, semantic, structure-aware)
  2. Loading and parsing documents (PDF, HTML, tables, OCR)
  3. Metadata and filtering
  4. Retrieval: top-k, MMR, similarity threshold
  5. Hybrid search (BM25 plus vector)

4.3 Better retrieval and answers

Topics to cover, in this order:

  1. Reranking with cross-encoders
  2. Query transformation: rewriting, multi-query, HyDE
  3. Building the final prompt with context and citations
  4. Advanced RAG: parent-child chunks, contextual retrieval, multi-hop
  5. Agentic RAG and Graph RAG

4.4 Quality, security and scale

Topics to cover, in this order:

  1. RAG evaluation: precision, recall, faithfulness, relevance (RAGAS)
  2. Freshness: updating the index, deletes and versioning
  3. Security: access control and PII in RAG
  4. Scaling RAG: cost, latency, caching
  5. Common RAG failures and how to debug them

4.1 RAG foundations — detailed notes

1. Why RAG: vs fine-tuning vs long context

LIKE I'M 5

RAG is an open-book exam. Fine-tuning is teaching a student a new habit. Long context is giving the student a very large desk.

EXPLAINED SIMPLY

  • Retrieval-Augmented Generation (RAG) retrieves relevant external information and places it in the model's context before generation.
  • Use RAG when answers must use changing, private or source-specific documents and need citations.
  • Fine-tuning changes model behaviour or weights; it is not the best way to keep frequently changing facts current.
  • Long context can hold more material, but costs more and does not guarantee every detail is noticed.
  • RAG adds ingestion, retrieval, permissions and freshness work. Fine-tuning adds dataset and training work.

COMPARE WITH LOOKALIKES

ApproachChangesBest fit
PromptingInstructionsBehaviour and format
RAGSupplied evidence at request timeFresh/private knowledge
Fine-tuningModel weightsRepeated behaviour/style
Long contextAmount of inputLarge bounded documents

INTERVIEW LENS

Choose RAG for changing knowledge, fine-tuning for behaviour, and long context when the needed source fits and retrieval is unnecessary.

TRAPS

RAG does not train the model. Fine-tuning does not automatically add live knowledge. Long context is not perfect recall.

ONE-LINE RECAP

RAG connects a model to external knowledge at answer time.

2. The RAG pipeline end to end

LIKE I'M 5

Prepare books, cut them into useful pages, make a catalogue, find the right pages, then answer using them.

EXPLAINED SIMPLY

  • Ingestion: load source files, extract text, clean it and preserve metadata.
  • Chunking: split content into pieces that can be retrieved independently.
  • Embedding and indexing: convert chunks to vectors and store them with IDs and metadata.
  • Retrieval: embed the user query and fetch likely relevant chunks.
  • Optional reranking: reorder candidates with a stronger relevance model.
  • Generation: place selected evidence into a prompt and ask the LLM to answer.
  • Post-processing: validate citations, permissions, format and answer quality.
  • Keep document IDs, versions and source locations so updates and deletes are possible.

TRY IT

const chunks = await retrieve(query);
const evidence = await rerank(query, chunks);
const answer = await generateAnswer({ query, evidence });

INTERVIEW LENS

Walk through offline ingestion and online query paths separately. Explain where metadata filters and access control run.

TRAPS

Bad parsing or chunking cannot be fixed by a better LLM. Never retrieve across tenant boundaries.

ONE-LINE RECAP

RAG is a data pipeline plus a retrieval-and-generation request path.

3. Embeddings deep dive and similarity

LIKE I'M 5

A map puts nearby places close together. An embedding map puts related meanings close in a mathematical space.

EXPLAINED SIMPLY

  • An embedding model maps text into a fixed-length vector.
  • Cosine similarity compares vector direction. Dot product combines direction and magnitude. Euclidean distance measures straight-line distance.
  • Normalisation changes how dot product relates to cosine similarity.
  • Similarity scores are model-specific; do not assume a universal threshold.
  • Query and document embeddings must come from compatible models and settings.
  • Evaluate retrieval using labelled queries and relevant documents.

TRY IT

const dot = a.reduce((sum, x, i) => sum + x * b[i], 0);
const norm = v => Math.sqrt(v.reduce((s, x) => s + x*x, 0));
const cosine = dot / (norm(a) * norm(b));

INTERVIEW LENS

Explain vector geometry, normalisation and why thresholds must be calibrated on domain data.

TRAPS

High similarity does not prove factual relevance. Different embedding spaces are not interchangeable.

ONE-LINE RECAP

Embeddings make semantic comparison possible, but evaluation determines whether retrieval is useful.

4. Vector databases and libraries

LIKE I'M 5

A normal database stores rows. A vector database adds a fast way to find rows with similar number patterns.

EXPLAINED SIMPLY

  • Vector stores save embeddings plus IDs and metadata, then search for nearest vectors.
  • Options include managed services and self-hosted systems such as Pinecone, Weaviate, Qdrant, Chroma, pgvector, FAISS and Milvus.
  • PostgreSQL with pgvector can be attractive when relational data and vectors belong together.
  • FAISS is a vector-search library, not a full managed database service.
  • Compare filtering, scale, backups, consistency, operations, tenancy, pricing and ecosystem.
  • Store source text or a reliable pointer to it; vectors alone cannot reconstruct the original document.

INTERVIEW LENS

Choose based on scale, filters, deployment, operational skill and existing database architecture.

TRAPS

A vector database is not automatically the best choice. Check metadata-filter behaviour and backup/restore.

ONE-LINE RECAP

Select vector storage by workload and operations, not hype.

5. Indexing: HNSW, IVF and ANN

LIKE I'M 5

To find a house, you use a map and shortcuts instead of measuring every house one by one.

EXPLAINED SIMPLY

  • Nearest-neighbour search finds vectors closest to a query.
  • Exact search checks every vector and can become expensive at scale.
  • Approximate Nearest Neighbour (ANN) uses indexes to search faster while accepting some recall loss.
  • HNSW builds a navigable multi-layer graph of nearby vectors.
  • IVF clusters vectors into lists and searches selected clusters.
  • Index parameters trade memory, speed and recall. Tune with real query distributions.
  • Measure Recall@k against exact search on a sample, plus latency and memory.

INTERVIEW LENS

Explain that ANN improves speed by avoiding exhaustive comparisons and trades some recall for performance.

TRAPS

Approximate does not mean random. Index quality depends on tuning and data shape.

ONE-LINE RECAP

ANN indexes accelerate vector search through structured shortcuts.

4.2 Preparing and retrieving data — detailed notes

6. Chunking strategies

LIKE I'M 5

A giant textbook is hard to search. Divide it into useful pages, but do not cut a sentence in half.

EXPLAINED SIMPLY

  • Chunking splits documents into retrievable units.
  • Fixed-size chunking is simple but can split tables or ideas.
  • Overlap preserves context across boundaries but duplicates tokens and storage.
  • Structure-aware chunking respects headings, paragraphs, code blocks and table boundaries.
  • Semantic chunking uses meaning changes to choose boundaries, but adds complexity.
  • Parent-child retrieval can search small chunks and return a larger surrounding section.
  • Tune chunk size and overlap using retrieval and answer evaluation, not a universal rule.

INTERVIEW LENS

Discuss semantic coherence, token limits, retrieval precision, overlap cost and document structure.

TRAPS

Too-small chunks lose context; too-large chunks dilute relevance. Tables and code need special handling.

ONE-LINE RECAP

Chunk by meaning and structure, then measure retrieval quality.

7. Loading and parsing PDFs, HTML, tables and OCR

LIKE I'M 5

Before searching a book, you must read the pages correctly. A scanned photo needs text recognition first.

EXPLAINED SIMPLY

  • A loader reads a source format. A parser extracts usable text and structure.
  • PDFs may contain selectable text, scanned images, tables, headers and multi-column layouts.
  • OCR converts image text into machine-readable text and can introduce recognition errors.
  • HTML parsing should remove navigation noise while preserving headings and links.
  • Tables need row/column structure; flattening them can destroy relationships.
  • Keep source page, URL, section, timestamps and extraction version as metadata.
  • Validate extraction with samples and compare against original files.

INTERVIEW LENS

Explain format-specific parsing, OCR, layout preservation, metadata and extraction quality checks.

TRAPS

A successful file load does not mean correct extraction. Scanned PDFs need OCR.

ONE-LINE RECAP

RAG quality begins with faithful document extraction.

8. Metadata and filtering

LIKE I'M 5

A library catalogue tells you which shelf, author and year a book belongs to.

EXPLAINED SIMPLY

  • Metadata describes a chunk: document ID, owner, department, date, source, type and version.
  • Metadata filters narrow retrieval to eligible documents before or during vector search.
  • Apply tenant and user permissions on the server, not based on model judgement.
  • Filters can improve relevance and prevent cross-user data leakage.
  • Index frequently filtered fields efficiently and test filter combinations.
  • Keep metadata consistent across ingestion, updates and deletes.

INTERVIEW LENS

Explain pre-filtering versus post-filtering and how access control must constrain the candidate set.

TRAPS

Never trust a user-supplied tenant ID. Filtering after retrieval can leak snippets into logs or prompts.

ONE-LINE RECAP

Metadata makes retrieval precise, fresh and permission-aware.

9. Retrieval: top-k, MMR and similarity threshold

LIKE I'M 5

Instead of bringing ten nearly identical pages, bring a few useful pages that cover different parts of the question.

EXPLAINED SIMPLY

  • Top-k returns the k highest-ranked candidates.
  • A similarity threshold rejects candidates below a calibrated score.
  • Maximal Marginal Relevance (MMR) balances relevance with diversity to reduce near-duplicates.
  • Larger k improves coverage but increases context size and noise.
  • Smaller k is cheaper but may miss evidence.
  • Tune k, thresholds and MMR using labelled queries, including questions with no answer in the corpus.

INTERVIEW LENS

Explain the relevance-diversity trade-off and why thresholds are dataset-specific.

TRAPS

Top-k always returns k items even when none is useful. Similarity scores are not calibrated probabilities.

ONE-LINE RECAP

Retrieval settings balance coverage, relevance, diversity and context cost.

10. Hybrid search: BM25 plus vectors

LIKE I'M 5

A librarian searches both exact book titles and books with similar meaning.

EXPLAINED SIMPLY

  • BM25 is a lexical ranking method based on term matching and term importance.
  • Vector search retrieves semantically related content even when wording differs.
  • Hybrid search combines lexical and semantic rankings.
  • It is useful for product codes, names, error messages and natural-language questions.
  • Combine rankings with a method such as reciprocal rank fusion, or learn a ranking model.
  • Evaluate lexical-only, vector-only and hybrid results on the same query set.

INTERVIEW LENS

Explain why lexical matching catches exact terms while vectors capture semantic similarity.

TRAPS

Hybrid search is not always better; tune weights and filters for the corpus.

ONE-LINE RECAP

Combine exact-term and meaning-based retrieval when both matter.

4.3 Better retrieval and answers — detailed notes

11. Reranking with cross-encoders

LIKE I'M 5

First find 20 possible books quickly. Then ask an expert to read each candidate with your question and rank them.

EXPLAINED SIMPLY

  • A bi-encoder embeds query and document separately for fast retrieval.
  • A cross-encoder reads the query and candidate together and scores their relevance.
  • Reranking improves ordering after initial retrieval.
  • It is slower per candidate, so rerank a limited shortlist.
  • Measure ranking quality, latency and cost.

INTERVIEW LENS

Describe retrieve-then-rerank and why cross-encoders are more precise but more expensive.

TRAPS

Reranking cannot recover a relevant document that initial retrieval never found.

ONE-LINE RECAP

Use rerankers to improve the order of retrieved candidates.

12. Query transformation: rewriting, multi-query and HyDE

LIKE I'M 5

A librarian may rewrite a vague question into clearer search phrases before searching.

EXPLAINED SIMPLY

  • Query rewriting turns conversational or ambiguous questions into search-friendly text.
  • Multi-query generates several query variants to improve coverage.
  • HyDE creates a hypothetical answer/document and embeds it to find similar real documents.
  • These methods can improve recall but add latency and may introduce wrong assumptions.
  • Preserve the user's original intent and compare transformed queries against original retrieval.
  • Never treat hypothetical text as evidence.

INTERVIEW LENS

Explain how query expansion addresses vocabulary mismatch and why generated hypothetical content must not be cited as source evidence.

TRAPS

Query expansion can drift from intent. HyDE output is a retrieval aid, not a factual source.

ONE-LINE RECAP

Transform queries to improve retrieval, but ground final answers in actual documents.

13. Final prompt with context and citations

LIKE I'M 5

Give the student the question and the exact pages they are allowed to use, then ask them to show where each answer came from.

EXPLAINED SIMPLY

  • Build a prompt containing the task, retrieved passages, source identifiers and answer rules.
  • Tell the model to answer only from supplied evidence when the task requires grounding.
  • Ask for citations linked to chunk IDs, page numbers or URLs.
  • Validate that every cited source exists and supports the associated claim.
  • If evidence is weak, ask the model to abstain or request clarification.
  • Keep citation formatting separate from source verification.

INTERVIEW LENS

Explain evidence-grounded generation and post-generation citation validation.

TRAPS

A model can invent citations or cite a real source that does not support the claim.

ONE-LINE RECAP

Citations must map to retrieved evidence and be checked.

14. Advanced RAG: parent-child, contextual retrieval and multi-hop

LIKE I'M 5

Find a small paragraph, but bring the whole chapter section so the answer has enough context.

EXPLAINED SIMPLY

  • Parent-child retrieval indexes small child chunks but returns a larger parent section.
  • Contextual retrieval adds useful document context to chunks before indexing.
  • Multi-hop retrieval performs a sequence of searches where one result helps form the next query.
  • These methods help when meaning spans sections or questions require linked facts.
  • They add complexity, tokens and more failure points.
  • Preserve original text and provenance so enriched context does not become fabricated source content.

INTERVIEW LENS

Explain how each method addresses lost context or multi-step information needs.

TRAPS

Contextual text must not overwrite the source. Multi-hop searches need bounded loops.

ONE-LINE RECAP

Advanced RAG improves context and multi-step retrieval at added complexity.

15. Agentic RAG and Graph RAG

LIKE I'M 5

A helper can decide which shelf to search next. A graph connects people, places and events like a relationship map.

EXPLAINED SIMPLY

  • Agentic RAG lets a model plan or choose retrieval actions, such as search, refine, fetch and verify.
  • Graph RAG uses entities and relationships to retrieve connected facts.
  • Graphs help with questions involving relationships across many documents.
  • Agentic retrieval can improve complex queries but increases tool calls, latency and unpredictability.
  • Use fixed retrieval pipelines for simple, repeatable questions.
  • Evaluate answer quality, evidence coverage, number of tool calls and failure rate.

INTERVIEW LENS

Compare fixed RAG, agentic retrieval and graph-based retrieval by query complexity and operational cost.

TRAPS

Agentic does not mean automatically more accurate. Graph extraction can create wrong relationships.

ONE-LINE RECAP

Use adaptive or graph retrieval only when query complexity justifies it.

4.4 Quality, security and scale — detailed notes

16. RAG evaluation: precision, recall, faithfulness and RAGAS

LIKE I'M 5

Check whether the right pages were found, whether the answer used them and whether the answer actually answered the question.

EXPLAINED SIMPLY

  • Precision@k asks how many retrieved results are relevant.
  • Recall@k asks how many of all relevant results were retrieved.
  • Faithfulness measures whether claims are supported by provided context.
  • Answer relevance measures whether the answer addresses the question.
  • Context relevance checks whether retrieved passages are useful.
  • RAGAS is one evaluation framework; metric definitions and implementations should be checked in current docs.
  • Combine automated metrics, labelled test sets and human review.

INTERVIEW LENS

Separate retrieval metrics from generation metrics and evaluate both stages independently.

TRAPS

A fluent answer can have poor retrieval grounding. LLM judges can be biased.

ONE-LINE RECAP

Measure retrieval and answer quality separately, then together.

17. Freshness: updates, deletes and versioning

LIKE I'M 5

When a library gets a new edition, remove the old copy from the catalogue and add the new one.

EXPLAINED SIMPLY

  • Store document IDs, versions, timestamps and source checksums.
  • On update, re-parse, re-chunk and re-embed affected content.
  • On delete, remove vectors and cached copies, and invalidate derived summaries where required.
  • Use idempotent ingestion so retries do not create duplicates.
  • Consider eventual consistency: a deleted document may remain briefly in replicas or caches.
  • Keep audit logs and support rollback to a known index version.

INTERVIEW LENS

Explain incremental ingestion, idempotency, tombstones, cache invalidation and index versioning.

TRAPS

Deleting the source file does not automatically delete embeddings. Stale caches can return old data.

ONE-LINE RECAP

Treat the vector index as a derived dataset that needs lifecycle management.

18. Security: access control and PII in RAG

LIKE I'M 5

A library card should only let you see books you are allowed to borrow.

EXPLAINED SIMPLY

  • PII is personally identifiable information such as names, contact details or identifiers.
  • Enforce access control before retrieval and again before returning content.
  • Use tenant-aware metadata filters and server-derived identity, never user-provided permission claims.
  • Minimise sensitive data, redact when appropriate and encrypt data in transit and at rest.
  • Review provider retention, logging, backups, residency and deletion policies.
  • Test cross-tenant attacks and prompt injection inside retrieved documents.

INTERVIEW LENS

Explain identity propagation, row-level filtering, least privilege, PII minimisation and auditability.

TRAPS

Filtering only after generation is too late. Logs and caches can leak data too.

ONE-LINE RECAP

Security must constrain ingestion, indexing, retrieval, generation, logs and deletion.

19. Scaling RAG: cost, latency and caching

LIKE I'M 5

A busy library needs more counters, shortcuts and prepared shelves so everyone is not waiting.

EXPLAINED SIMPLY

  • Profile ingestion, embedding, vector search, reranking, model generation and network time separately.
  • Batch embeddings during ingestion when supported.
  • Cache stable query embeddings, retrieval results or final answers only when permissions and freshness allow.
  • Use smaller candidate sets, rerank only the shortlist and cap context tokens.
  • Scale vector storage and model serving independently.
  • Track p95 latency, cost per answer, cache hit rate, index size and concurrency.

INTERVIEW LENS

Describe bottleneck measurement, batching, caching, candidate limits and independent scaling.

TRAPS

Cache keys must include user/tenant scope where necessary. Cached answers can become stale.

ONE-LINE RECAP

Optimise each pipeline stage and preserve permission and freshness guarantees.

20. Common RAG failures and debugging

LIKE I'M 5

If the answer is wrong, check whether the book was read correctly, the right page was found or the student misunderstood it.

EXPLAINED SIMPLY

  • Bad extraction: inspect source parsing and OCR.
  • Bad chunks: inspect boundaries, overlap and metadata.
  • Bad retrieval: inspect query, filters, top-k, embeddings and ranking.
  • Bad generation: inspect prompt, evidence order, context budget and model choice.
  • Bad citations: map citations to source spans and verify support.
  • Wrong permissions: inspect identity propagation and filters before generation.
  • Log trace IDs, source IDs, model version, prompt version and timings without logging unnecessary sensitive content.
  • Build a reproducible failing query and add it to the golden set.

INTERVIEW LENS

Debug from source ingestion to final response, isolating each stage with traces and measurable checks.

TRAPS

Do not fix every failure by changing the prompt. Diagnose the stage first.

ONE-LINE RECAP

Trace the full pipeline and identify the failing stage before changing anything.

Part 4 cheat sheet — interview answers

  1. RAG → Retrieve external evidence and place it in model context before generation.
  2. RAG vs fine-tuning → Knowledge at request time vs behaviour encoded in weights.
  3. Chunking → Split by semantic and document structure, then evaluate.
  4. Embeddings → Vector representations used for semantic retrieval.
  5. HNSW/IVF → ANN indexes that trade recall, memory and speed.
  6. BM25 + vectors → Exact-term and semantic retrieval complement each other.
  7. Reranker → Scores query-document pairs to reorder candidates.
  8. MMR → Balances relevance with diversity.
  9. HyDE → Hypothetical text aids retrieval but is not evidence.
  10. Citations → Must map to real source spans and support claims.
  11. Agentic RAG → Model chooses retrieval actions for complex questions.
  12. RAGAS → Framework with metrics for retrieval and answer evaluation.
  13. Freshness → Versioned ingestion, updates, deletes and cache invalidation.
  14. RAG security → Enforce tenant permissions before retrieval and at response time.
  15. Debugging → Trace ingestion, chunking, retrieval, generation and citations.