Sub topic 12
Using a vector database for retrieval-augmented generation
Retrieval-augmented generation (RAG) gives a language model facts it was not trained on. The system looks up relevant text in your own data, then puts that text in the prompt. This chapter assumes you know what an embedding is, how cosine similarity ranks vectors, and that a vector index returns approximate nearest neighbors. It covers how a vector database fits into a RAG system, the decisions that most affect answer quality, and the errors that show up most often.
Why RAG needs a vector database
A language model has a fixed training cutoff and no access to your private documents. You could paste every document into the prompt, but the context window is limited, long prompts cost more, and models use information in the middle of a very long prompt less reliably.
RAG selects only the few passages that matter for each question. The vector database does the selecting. It stores one embedding per passage, and at query time it returns the passages whose embeddings are closest to the question's embedding. The model then answers from those passages.
Embeddings capture meaning, not exact wording. A question such as "Can I get my money back?" can match a passage titled "Refund policy" even though they share no keywords.
The two pipelines
A RAG system has an ingestion pipeline that runs when documents change and a query pipeline that runs for each question.
Both embedding steps must use the same model. Vectors from different models live in different spaces, and comparing them gives meaningless scores. Most embedding models also produce vectors of different lengths, so a mismatch often fails loudly with a dimension error. If two models happen to share a dimension, nothing fails and results are quietly wrong.
Ingestion: chunking
You do not embed whole documents. A single vector for a 40-page manual blends many topics and matches none of them well. Instead you split documents into chunks, each small enough to be about one thing.
Chunking is the decision that most affects retrieval quality, and it has no universal best setting.
| Choice | Smaller chunks | Larger chunks |
|---|---|---|
| Precision | Each vector is focused, so matches are sharper | Vectors blend several topics |
| Context | A chunk may lack the surrounding facts needed to answer | A chunk is more self-contained |
| Index size | More vectors, more memory | Fewer vectors |
| Prompt cost | Cheap per chunk, so you can fit more of them | Each chunk uses much of the prompt budget |
Common practice is a few hundred tokens per chunk, with an overlap of 10 to 20 percent between neighbors so a sentence cut at a boundary still appears whole in one chunk. Where possible, split on structure such as headings and paragraphs before falling back to a fixed size.
Each chunk is stored as a record with three parts:
- The vector.
- The original chunk text, because the model needs text, not numbers.
- Metadata such as source document ID, chunk position, title, date, language, and access group.
The metadata is what makes filtering, citation, and updates possible. The chapter on metadata filtering covers how filters interact with the index.
A minimal retrieval pipeline
The following program runs with only NumPy. The embed function is a stand-in. It hashes words into a fixed-size count vector, so it matches shared words rather than meaning. In a real system you would replace it with a call to an embedding model and keep everything else the same.
import re
import zlib
import numpy as np
DIM = 512
def embed(text):
"""Toy embedding: hashed word counts, unit length."""
vec = np.zeros(DIM, dtype="float32")
for token in re.findall(r"[a-z0-9]+", text.lower()):
vec[zlib.crc32(token.encode()) % DIM] += 1.0
norm = np.linalg.norm(vec)
return vec / norm if norm else vec
def chunk(text, size=25, overlap=5):
words = text.split()
step = size - overlap
return [" ".join(words[i:i + size])
for i in range(0, max(len(words) - overlap, 1), step)]
documents = {
"refunds.md": (
"Customers can request a refund within 30 days of purchase. "
"Refunds are issued to the original payment method and take "
"five to seven business days to appear. Digital goods that "
"have been downloaded are not eligible for a refund."
),
"shipping.md": (
"Standard shipping takes three to five business days. "
"Express shipping arrives in one to two business days and "
"costs extra. Orders over fifty dollars ship free with the "
"standard option."
),
}
# Ingestion: one record per chunk, with text and metadata.
records = []
for source, text in documents.items():
for position, piece in enumerate(chunk(text)):
records.append({"source": source, "position": position, "text": piece})
matrix = np.stack([embed(r["text"]) for r in records])
def retrieve(question, k=2):
scores = matrix @ embed(question) # unit vectors: dot product = cosine
top = np.argsort(-scores)[:k]
return [(records[i], float(scores[i])) for i in top]
def build_prompt(question, hits):
context = "\n".join(
f"[{r['source']}#{r['position']}] {r['text']}" for r, _ in hits
)
return (
"Answer using only the context below. Cite sources in brackets. "
"If the context does not contain the answer, say so.\n\n"
f"Context:\n{context}\n\nQuestion: {question}\nAnswer:"
)
question = "How long do refunds take to arrive?"
print(build_prompt(question, retrieve(question)))The program prints a prompt that you would send to a language model. The search here is exact. At scale you replace the matrix product with an index query, and the surrounding code stays the same.
Building the prompt
Retrieval returns candidates. The prompt is where you decide how to use them.
- Number of chunks (k). Too few risks missing the answer. Too many dilutes the prompt with irrelevant text and raises cost. Start with 3 to 8 and measure.
- Instructions. Tell the model to answer only from the context and to say when the context is insufficient. Without this, the model fills gaps from its own memory, which is the behavior RAG is meant to reduce.
- Source labels. Tag each chunk with an identifier so the model can cite it and users can verify the answer.
- Ordering. Place the strongest chunks first or last. Models attend less to the middle of long contexts.
- Token budget. Count tokens before sending. If retrieved text exceeds the budget, drop the lowest-scoring chunks rather than cutting one in half.
A score threshold is a useful guard. If the best similarity is low, the knowledge base probably does not contain the answer, and the system should say so instead of passing weak matches to the model. The right threshold depends on the embedding model, so choose it from examples of answerable and unanswerable questions.
Features of the database that matter for RAG
A bare index returns IDs and scores. A RAG system needs more from the database layer.
- Payload storage. The chunk text and metadata come back with the hit, with no second lookup needed.
- Filtered search. Restrict results by tenant, document type, date, or language. For multi-user systems, filter by access permissions before results reach the prompt, not after the model has seen them.
- Updates by document. When a document changes, delete all its old chunks by source ID and insert the new ones. If you skip the delete, stale and current versions both stay searchable and may contradict each other.
- Hybrid search. Keyword matching catches exact terms such as product codes, error messages and names that embeddings handle poorly. Combining both is common in production RAG.
- Reranking. A common pattern retrieves 30 to 100 candidates quickly, then reorders them with a slower, more accurate model before taking the top few for the prompt.
Common failure modes
| Symptom | Likely cause | What to check |
|---|---|---|
| The answer exists but is never retrieved | Chunk too large or too small, or the question wording is far from the document wording | Inspect the top 20 hits for known questions. Try hybrid search or query rewriting |
| The right chunk is retrieved but the answer is wrong or incomplete | The needed facts are split across chunks, or the prompt is cluttered | Increase overlap, use larger chunks, or retrieve neighboring chunks |
| Answers cite outdated facts | Old chunks were never deleted | Delete by source ID before re-ingesting |
| Results are poor across the board | The query and the documents were embedded with different models or settings | Confirm the same model, version, and normalization |
| The model invents an answer when nothing relevant exists | No threshold and no refusal instruction | Add a score cutoff and an explicit "say you don't know" instruction |
| Users see content they should not | Access control applied after retrieval | Filter inside the database query |
Evaluating a RAG system
Evaluate retrieval separately from generation. If retrieval fails, no prompt can fix it, and mixing the two hides where the problem is.
- Build a test set of real questions, each labeled with the chunk or document that contains the answer.
- Measure retrieval with recall@k (the share of questions whose correct chunk is in the top k) and, if order matters, mean reciprocal rank.
- Only then judge answers: whether they are correct, supported by the cited text, and appropriately refuse when information is missing.
This is a different recall from the one that compares an approximate index to exact search. Index recall tells you whether the index finds the true nearest neighbors. Retrieval recall tells you whether the true nearest neighbors include the answer. A system can have perfect index recall and still fail if the embedding model or chunking is poor, so measure both.
Other uses of the same machinery
The pattern of embedding items and searching by closeness is not limited to question answering. The same database serves semantic search over products or support tickets, recommendations ("more like this"), duplicate detection, and long-term memory for agents that store past interactions and recall the relevant ones. The ingestion, filtering, and update concerns above apply to each.
Exercise
A RAG system returns an old return policy even though the policy document was updated last week. The ingestion job re-embeds the new file and inserts its chunks. What is the most likely cause, and what is the fix?
Show answer
The job only inserts. The old chunks from the previous version are still in the database, so they remain searchable next to the new ones. The fix is to delete every chunk with that document's source ID before inserting the new chunks, or to upsert chunks under stable IDs and delete any that no longer exist. This requires storing the source ID as metadata at ingestion time.
Exercise
In the Python example, the question "Can I get my money back?" retrieves a poor match for the refund passage. Why does this happen with that code, and what change would address it?
Show answer
The toy embed function counts shared words. The question has almost no words in common with the refund text, so the vectors are nearly orthogonal and the similarity is low. A real embedding model maps both phrases to nearby vectors because they mean similar things. Replacing embed with a real model, used for both chunks and queries, is the fix. Hybrid search or query rewriting could also help.