What Is RAG? Retrieval-Augmented Generation and Vector Search
By LatestLLM Editorial · Published · Facts verified · 8 min read
Also called: retrieval-augmented generation, RAG, vector database, semantic search, chunking, cosine similarity, HNSW
Before this: Embedding, Context window
In one line
Retrieval-augmented generation looks up the passages most relevant to a question using embeddings, then gives them to a language model so it answers from those sources.
RAG and vector search, simply and technically
In plain English
A language model knows what it learned in training and nothing about your company's documents, yesterday's news or a manual released last week. Retrieval-augmented generation, or RAG, solves this by looking things up first. When you ask a question, a search step finds the few passages most relevant to it, and those passages are pasted into the prompt along with your question so the model can answer from them.
The search is not keyword matching. Both the question and the passages are converted to lists of numbers that capture meaning, and the search finds passages whose numbers are close to the question's. That is why a question about “kitten sleeping” can find a passage about “a cat resting”.
Think of it like this: RAG is an open-book exam. Without it the model answers from memory and can misremember. With it, a librarian first fetches the few relevant pages and lays them open on the desk, and the model answers while reading them. The open book helps only if the librarian brings the right pages: if retrieval fetches the wrong ones, the model can still answer confidently from them. A real librarian also knows when she has found nothing, which search often does not.
Everyday example: Finding the right passage
A company has 300 pages of manuals and someone asks, “How do I reset the router?”
Input:
“How do I reset the router?” + 300 pages of manuals
Output:
5 relevant chunks in the prompt, an answer based on them
What it shows: The search step converts the question to numbers, compares them with numbers for each small chunk of the manuals, and returns the five closest chunks. Those five chunks, a few thousand words in all, are placed in the prompt. The model reads them and answers, instead of reading all 300 pages or guessing.
Technically
RAG (Lewis et al. 2020) combines a generator with non-parametric memory: documents are split into chunks, each chunk is embedded as a vector, and the vectors are stored in an index. At query time the question is embedded with the same model, the k nearest chunks by cosine similarity are retrieved and the generator is conditioned on them. With all-MiniLM-L6-v2, vectors have 384 dimensions and are normalised, so cosine similarity is a dot product: the real sentence vectors for “The cat sat on the mat.” and “A kitten is sleeping on the rug.” score 0.526 against 0.075 for “The stock market fell sharply today.”
Exact search compares the query with every vector, O(N · d). Approximate nearest-neighbour indexes such as HNSW (Malkov and Yashunin) build a multi-layer graph for near-logarithmic search. Chunk size and overlap trade precision against context: chunks that are too small lose meaning and too large dilute the match, and the retrieved text must fit the prompt budget, system instructions plus question plus k times the chunk size. Placement matters because models use the start and end of long contexts better than the middle.
Technical example: Index size and prompt budget
Chunk counts for three document collections with 256-token chunks and 10% overlap, the storage for 384-number float32 vectors, and the prompt size for five retrieved chunks. One page is assumed to hold 500 words at 0.75 words per token.
Code (python):
def chunks(doc_tokens, size, overlap):
return 1 if doc_tokens <= size else -(-(doc_tokens - overlap) // (size - overlap))
tokens_per_page = round(500 / 0.75)
for name, pages in [("10-page memo", 10), ("300-page manual", 300), ("5,000-page library", 5000)]:
n = chunks(pages * tokens_per_page, 256, 26)
print(f"{name:19s} {pages * tokens_per_page:>9,} tokens -> {n:>6,} chunks, {n * 384 * 4 / 1e6:6.2f} MB of vectors")
prompt = 300 + 50 + 5 * 256 # instructions + question + five chunks
print(f"prompt with 5 chunks: {prompt:,} tokens = {100 * prompt / 131072:.2f}% of a 131,072-token window")
Output:
10-page memo 6,670 tokens -> 29 chunks, 0.04 MB of vectors
300-page manual 200,100 tokens -> 870 chunks, 1.34 MB of vectors
5,000-page library 3,335,000 tokens -> 14,500 chunks, 22.27 MB of vectors
prompt with 5 chunks: 1,630 tokens = 1.24% of a 131,072-token window
What it shows: A 300-page manual becomes about 870 chunks and 1.3 MB of vectors, small enough to search exactly. The prompt with five retrieved chunks uses about 1.2% of a 131,072-token window, whereas pasting the whole manual (about 200,000 tokens) would not fit at all, and the 5,000-page library would be roughly 3.3 million tokens.
Retrieve, then read
In plain English: RAG splits a hard job into two easier ones. A search system finds a few relevant passages from a huge library, and the language model reads those passages and writes an answer. Each part does what it is good at.
Technically:
Lewis et al. describe the motivation: pre-trained models store factual knowledge in their parameters but their ability to access and precisely manipulate it is limited, providing provenance is hard and updating knowledge is an open problem. Pairing a generator with an explicit non-parametric memory addresses all three: sources can be cited, and the index can be updated without retraining.
In practice the pipeline is: split documents, embed chunks, store them, embed the question, retrieve the top k, build a prompt with the passages and instructions to answer only from them, and generate. Quality depends on every step, and most failures are retrieval failures rather than generation failures.
Embeddings and similarity
In plain English: Search by meaning works because an embedding model places similar texts near each other. A question and a passage that talk about the same thing get similar lists of numbers, even if they share no words.
Technically:
For normalised embeddings cosine similarity is the dot product, between −1 and 1. The all-MiniLM-L6-v2 model gives 0.526 for “The cat sat on the mat.” against “A kitten is sleeping on the rug.” and 0.075 and 0.036 for these against “The stock market fell sharply today.” Thresholds are model-specific, so rankings matter more than absolute values.
Models trained for retrieval embed queries and passages so that questions land near their answers rather than near other questions. Hybrid systems combine vector scores with keyword scores such as BM25, since exact terms like product codes and names are easier for keyword search, and add a re-ranker that rescores the top candidates with a more accurate model.
What is cosine similarity?
A measure of the angle between two vectors: 1 means the same direction, 0 means unrelated, and negative values mean opposite directions.
Chunking and indexes
In plain English: Documents are cut into pieces before they are indexed, because a whole book has too many topics to match a single question. The pieces should be big enough to make sense alone and small enough to be specific.
Technically:
Chunks of a few hundred tokens with 10 to 20% overlap are a common starting point; overlap prevents a sentence at a boundary from being cut off from its context. Structure-aware chunking splits on headings and paragraphs, and metadata such as source, date and section can be stored for filtering and citation.
At scale, exact comparison against millions of vectors is slow. HNSW builds a hierarchy of proximity graphs so a search touches only a small part of the index; it trades a little recall for large speed gains. Index memory is vectors times dimensions times bytes: 384 float32 numbers per chunk is 1,536 bytes, so a million chunks is about 1.5 GB before graph overhead.
Everyday example: Too small, too big
A chunk is one sentence in one case and an entire chapter in another.
What it shows: A one-sentence chunk may miss the context needed to answer; a chapter-sized chunk matches many questions weakly and fills the prompt. Chunks of a few paragraphs balance the two.
Putting it in the prompt
In plain English: The retrieved text competes for the model's attention with everything else in the prompt. It works best when it is short, relevant and clearly separated from the question, with instructions to answer from it.
Technically:
The prompt budget is system text plus question plus k chunks; with 256-token chunks and k = 5 that is about 1,600 tokens, but k = 20 would be over 5,000. More is not always better: Liu et al. found that models use information at the start and end of a long context better than information in the middle, so adding marginal passages can hurt.
RAG does not make the model infallible. The model can ignore passages, misread them or fill gaps from memory. Requiring citations and allowing “not found in the documents” as an answer, as the hallucination page explains, reduces confident errors. Long context windows can replace retrieval for small collections, but cost and accuracy still favour retrieval for large ones.
Common misconceptions
Myth: RAG fine-tunes the model on your documents.
Reality: The model's weights are untouched. The relevant passages are retrieved at question time and placed in the prompt.
Myth: RAG stops hallucinations.
Reality: It reduces them by grounding answers in sources, but poor retrieval, ignored passages or gaps filled from memory can still produce wrong answers.
Myth: Vector search matches keywords.
Reality: It matches meaning through embeddings, so it finds related text with different words. It can miss exact identifiers, which is why hybrid search is common.
Key takeaways
- RAG retrieves the most relevant chunks of your documents with embeddings and puts them in the prompt, so the model answers from sources it never saw in training.
- Retrieval is semantic: sentences with similar meaning have nearby vectors, as with the real MiniLM scores 0.526 for the cat and kitten sentences against 0.075 for an unrelated one.
- Chunk size, overlap and top-k decide index size and how much of the context window the retrieved text uses.
- RAG reduces but does not eliminate hallucination: a wrong retrieval or a misread passage still yields a wrong answer.
Frequently asked questions
What is RAG?
Retrieval-augmented generation: searching a document collection for relevant passages and giving them to a language model in the prompt so it answers from them.
What is a vector database?
A store that keeps embedding vectors and finds the nearest ones to a query vector quickly, usually with an approximate index such as HNSW.
How big should chunks be?
Commonly a few hundred tokens with 10 to 20% overlap, tuned to the documents and the questions.
Is RAG better than a long context window?
For small collections a long window can hold everything. For large or changing collections retrieval is cheaper and often more accurate, since models use middle-of-context information less well.
Does RAG need fine-tuning?
No. It works with an off-the-shelf model, and the knowledge can be updated by changing the index.
Sources
Facts last verified November 23, 2026.
- Lewis et al.: Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks (arXiv)
- Malkov and Yashunin: Efficient and robust approximate nearest neighbor search using HNSW graphs (arXiv)
- Liu et al.: Lost in the Middle, How Language Models Use Long Contexts (arXiv)
- sentence-transformers/all-MiniLM-L6-v2 (Hugging Face)