
RAG Explained (2026): Embeddings, Chunking, Hybrid Search, and Vector Databases, Tested
Language models know a lot, but they do not know your documents. They have never read your internal wiki, your product manual, or last week’s support tickets. Ask about them, and a model either admits it does not know or, worse, invents a confident answer.
Retrieval-augmented generation, or RAG, fixes that with a simple idea. Before the model answers, your code searches your own documents, picks the most relevant passages, and puts them into the prompt. The model then answers from that material and cites it. Most “chat with your docs” products work this way.
The idea is simple, but the details decide whether it works. How you split documents, which search method you use, and how you instruct the model change the results dramatically. This guide explains each piece in plain terms, then shows measured results instead of rules of thumb.
I built a complete RAG pipeline and tested it on 16 articles from this blog, about 700,000 characters in total. Embeddings came from Google’s EmbeddingGemma, running locally through Ollama, and answers came from a local Gemma 4 model. I asked 24 questions with known answers and compared three chunking strategies and three search methods. The code needs no dependencies, and every number below comes from those runs on November 30, 2026.
This article belongs to my AI series. It pairs with my guides to running LLMs locally, evaluating prompts and agents, and prompt injection, which matters because RAG feeds untrusted documents straight into a model.
Table of Contents
- The Short Answer
- Do You Need RAG at All?
- The RAG Pipeline
- Embeddings Explained
- Chunking: The Step That Matters Most
- Keyword Search Still Matters
- My Test Results
- The Code
- Generating Grounded Answers
- Vector Databases
- Reranking and Contextual Retrieval
- Security and Permissions
- Running RAG in Production
- Common Mistakes
- Frequently Asked Questions
- Conclusion
- References
1. The Short Answer
| Decision | Recommendation |
|---|---|
| Chunking | Split on document structure, such as headings, and prefix each chunk with its title and heading path |
| Search | Use hybrid search: keyword (BM25) plus vectors, merged with reciprocal rank fusion |
| Embedding model | Pick one, use its documented query and document prefixes, and never mix models in one index |
| Vector database | Start with what you already run. pgvector in Postgres is enough for most teams |
| Generation | Tell the model to answer only from the sources, cite them, and say when it does not know |
| Evaluation | Measure retrieval and generation separately, with a set of questions whose answers you know |
My tests support the first two rows strongly. Heading-aware chunks with a heading path found the right passage in the top five results for all 24 questions. Fixed-size chunks managed 20 with keywords and only 17 with vectors.
2. Do You Need RAG at All?
RAG adds moving parts, so check whether you need it first.
Small document sets can go straight into the prompt. Anthropic’s write-up on contextual retrieval makes the point directly. If your knowledge base is smaller than about 200,000 tokens, roughly 500 pages, you can include all of it in the prompt. Prompt caching makes repeated use of the same large prompt much cheaper, as my cost optimization guide shows.
RAG earns its place when any of these is true.
- The material is too large for a context window, or too expensive to send with every request.
- It changes often, and you want answers to reflect the latest version without retraining anything.
- Different users may see different documents, so retrieval must respect permissions.
- You need citations, so users can check where an answer came from.
Fine-tuning is not a substitute. Fine-tuning changes how a model behaves, such as its tone or format. It is a poor way to teach facts, because facts baked into weights cannot be cited, updated, or permission-checked. Use RAG for knowledge and fine-tuning for behavior.
3. The RAG Pipeline
Every RAG system has two halves. Indexing happens ahead of time, and querying happens on every question.
INDEXING (ahead of time)
documents --> clean --> chunk --> embed --> store vectors + text + metadata
QUERYING (every question)
question --> embed --> vector search --+
\ +--> merge --> (rerank) --> top k chunks
+-> keyword search ----------+ |
v
prompt = instructions + sources + question --> model --> answer with citations
The stages are these.
- Clean: Strip navigation, boilerplate, and markup that adds noise. Keep headings, because they carry meaning.
- Chunk: Split each document into passages small enough to retrieve precisely.
- Embed: Turn each chunk into a vector, a list of numbers that captures its meaning.
- Store: Save the vectors with the chunk text and metadata, such as source, date, and permissions.
- Retrieve: Find the chunks most relevant to the question, using vectors, keywords, or both.
- Rerank: Optionally, reorder the best candidates with a slower, more accurate model.
- Generate: Give the top chunks to the language model with clear instructions, and return the answer with sources.
4. Embeddings Explained
An embedding model turns text into a fixed-length list of numbers. Texts with similar meanings land close together in that space, even when they share no words. “How do I reset my password?” and “I forgot my password, how can I change it?” end up near each other.
How closeness is measured
Most systems use cosine similarity, which compares the direction of two vectors. When vectors are normalized to length one, cosine similarity equals the plain dot product, which is cheap to compute. Ollama returned normalized vectors in my tests, which I confirmed by checking that a vector’s length was exactly 1.0000.
The model I used: EmbeddingGemma
EmbeddingGemma is Google’s small open embedding model. According to its model card, it has about 300 million parameters, produces 768-dimensional vectors, accepts up to 2,048 tokens, and covers more than 100 languages. It also supports Matryoshka truncation, which means you can keep only the first 512, 256, or 128 numbers of each vector to save storage, with some loss of quality.
On my machine, it embedded about 1,000 chunks in around 12 seconds through Ollama, at no cost.
Be precise about the version. Ollama’s embeddinggemma tag resolved to embeddinggemma:300m-bf16, the original text-only model, and that is what every number in this article comes from. Google has since released EmbeddingGemma 2, a larger multimodal model of about 740 million parameters under the Apache 2.0 license. I did not test it. If you use it, read its own model card, because limits and prompt formats can change between versions.
ollama pull embeddinggemma
Use the model’s prefixes
Many embedding models are trained with different formats for questions and documents. EmbeddingGemma’s model card documents two of them.
- For search queries:
task: search result | query: {question} - For documents:
title: {title or "none"} | text: {content}
Skipping these prefixes quietly lowers quality. Check the model card for the exact model and version you pull, because the formats differ between models, and sometimes between versions of the same model.
Choosing an embedding model
- Hosted models from OpenAI, Google, Cohere, Voyage AI, and others are easy to start with and strong on benchmarks. You pay per token and send your text to the vendor.
- Local models such as EmbeddingGemma run on your own hardware. They are free per call and keep data in-house, at the cost of running the infrastructure.
- Check the language support. If your documents are not in English, pick a model that is explicitly multilingual.
- Benchmarks are a starting point. The MTEB leaderboard compares models, but your own retrieval test, like the one in section 7, is what counts.
Never mix models in one index. Vectors from different models, or even different versions of one model, live in different spaces. If you change the embedding model, re-embed everything.
5. Chunking: The Step That Matters Most
A chunk is the unit your system retrieves. If a chunk is too big, it mixes several topics and matches nothing well. If it is too small, it loses the context that made it meaningful. Where you cut matters as much as how big the pieces are.
Common strategies
- Fixed-size windows: Cut every N characters or tokens, with some overlap. It is simple and ignores structure, so it often slices a sentence or a table in half.
- Recursive splitting: Try to split on paragraphs first, then sentences, then words, until pieces fit. Many frameworks use this as the default.
- Structure-aware splitting: Split on the document’s own structure, such as Markdown headings, HTML sections, or code functions.
- Semantic splitting: Use embeddings to find where the topic changes, and cut there.
- Late chunking and contextual retrieval: Give each chunk information about the whole document before embedding it. Section 11 covers these.
The trick that made the biggest difference
A chunk taken out of a long article often loses its subject. A paragraph that says “Seven days is a practical default” means nothing on its own. The same paragraph with a prefix like this one is easy to match.
Snyk vs Dependabot vs Renovate: The 2026 Dependency Scanning and Update Showdown
> 13. Frequently Asked Questions > What cooldown should I use?
Seven days is a practical default for most projects...
Prefixing every chunk with its document title and heading path is cheap. It needs no model calls, and in my tests it was the single biggest improvement.
6. Keyword Search Still Matters
Vector search finds meaning, but it is weak at exact tokens. Product codes, error messages, CVE numbers, and rare names often matter most, and an embedding may blur them. Keyword search handles those well.
BM25 in one paragraph
BM25 is the classic keyword ranking formula behind most search engines. It scores a chunk higher when it contains the query’s words, especially rare words, and it adjusts for chunk length, so long chunks do not win just by containing more text. It needs no model and no GPU.
Hybrid search with reciprocal rank fusion
Hybrid search runs both searches and merges the two ranked lists. The simplest robust merge is reciprocal rank fusion (RRF). Each chunk gets a score of 1 / (k + rank) from each list, usually with k = 60, and the scores are added. A chunk that ranks well in both lists rises to the top.
RRF only uses ranks, not raw scores. That matters, because BM25 scores and cosine similarities are on completely different scales and cannot be compared directly.
Some systems go further and give the keyword list and the vector list different weights, tuned on labeled questions. That can help once you have enough data to tune it reliably. Plain RRF, with equal weights, is the safe starting point, and it is what I used.
7. My Test Results
The setup
- Corpus: 16 articles from this blog on security and AI, about 706,550 characters of Markdown.
- Questions: 24, each with a known answer in a specific article. I phrased them differently from the text on purpose. For example, “Do I need to pay for LM Studio if I use it at my job?” for a passage about commercial licensing.
- Hit rule: A result counts as a hit when it comes from the right article and contains the answer phrase.
- Metrics: hit@1 is how often the first result was right. hit@5 is how often a right result appeared in the top five. MRR, mean reciprocal rank, rewards ranking the right chunk higher, from 0 to 1.
Three chunking strategies
- Strategy A, fixed windows: 1,000 characters with 150 characters of overlap. This produced 838 chunks.
- Strategy B, heading-aware with heading path: Split on
##and###headings, up to 1,500 characters, split further on paragraphs, and prefixed with the title and heading path. This produced 1,018 chunks. - Strategy C, heading-aware without the path: The same chunks as B, with the prefix removed. This isolates the effect of the prefix.
Results
| Chunking | Search | hit@1 | hit@5 | hit@10 | MRR |
|---|---|---|---|---|---|
| A. Fixed windows | BM25 | 12 | 20 | 24 | 0.659 |
| A. Fixed windows | Vector | 12 | 17 | 19 | 0.583 |
| A. Fixed windows | Hybrid | 13 | 20 | 23 | 0.666 |
| B. Headings with path | BM25 | 17 | 23 | 23 | 0.793 |
| B. Headings with path | Vector | 19 | 24 | 24 | 0.885 |
| B. Headings with path | Hybrid | 19 | 24 | 24 | 0.889 |
| C. Headings without path | BM25 | 13 | 23 | 24 | 0.702 |
| C. Headings without path | Vector | 16 | 23 | 23 | 0.788 |
| C. Headings without path | Hybrid | 15 | 23 | 24 | 0.775 |
What the numbers say
- Chunking mattered more than the search method. Moving from fixed windows to heading-aware chunks with a path raised vector hit@5 from 17 to 24 out of 24.
- The heading path alone was worth a lot. Removing it, in strategy C, dropped vector hit@1 from 19 to 16 and MRR from 0.885 to 0.788.
- Fixed windows hurt vector search the most. With them, vectors did worse than plain keywords. A window that starts mid-sentence produces a muddled embedding.
- Hybrid search was the safest choice. It was best or tied for best in every strategy on hit@5 and MRR.
A lesson about my own answer key
In my first run, one question failed every method. It asked how long to wait before adopting a new package version, and I had set the expected answer phrase to “7-day.” When I looked at the top result, it was exactly the right FAQ entry. That entry says “Seven days,” not “7-day,” so my grader marked a correct result as wrong.
After I accepted both phrasings, the best configuration scored a perfect 24 out of 24 at hit@5. The lesson applies to every evaluation: when a test fails, check the test before you change the system. My evals guide covers more examples like this.
Limits of this test
Twenty-four questions on 16 articles is a small test. It is good enough to show large differences, such as the effect of chunking, and not good enough to rank close options.
The corpus also gives heading-aware chunking a home-field advantage. All 16 articles are clean Markdown by one author, with consistent, descriptive headings. Do not expect a perfect 24 out of 24 on your own data. Scanned PDFs, chat logs, emails, and HTML with weak structure need more aggressive cleaning first. They also have few useful headings to split on, so they may benefit more from semantic chunking or model-written contextual descriptions, which section 11 covers.
8. The Code
Here is the complete retrieval code. It has no dependencies, and it only needs a local Ollama server with embeddinggemma pulled.
// rag.mjs: a small, dependency-free RAG retrieval pipeline.
// Embeddings come from a local Ollama server running the embeddinggemma model.
const OLLAMA = process.env.OLLAMA_URL ?? "http://127.0.0.1:11434";
// ---------- Chunking ----------
// Strategy A: fixed-size windows with overlap. Simple, structure-blind.
export function fixedChunks(doc, size = 1000, overlap = 150) {
const out = [];
for (let start = 0; start < doc.body.length; start += size - overlap) {
out.push({
doc: doc.slug,
title: doc.title,
text: doc.body.slice(start, start + size),
});
if (start + size >= doc.body.length) break;
}
return out;
}
// Strategy B: split on Markdown headings, keep sections whole when they fit,
// otherwise split on paragraph boundaries. Prefix each chunk with its heading path.
export function headingChunks(doc, max = 1500) {
const out = [];
const path = [];
let buf = [];
const flush = () => {
const text = buf.join("\n").trim();
buf = [];
if (!text) return;
const crumb = [doc.title, ...path.filter(Boolean)].join(" > ");
for (const piece of splitParagraphs(text, max)) {
out.push({
doc: doc.slug,
title: doc.title,
heading: crumb,
text: `${crumb}\n\n${piece}`,
});
}
};
let inCode = false;
for (const line of doc.body.split("\n")) {
if (line.startsWith("```")) inCode = !inCode;
const m = !inCode && line.match(/^(#{2,3})\s+(.*)/);
if (m) {
flush();
path.length = m[1].length - 1; // ## -> level 1, ### -> level 2
path[m[1].length - 2] = m[2].trim();
} else buf.push(line);
}
flush();
return out;
}
function splitParagraphs(text, max) {
const parts = [];
let cur = "";
for (const para of text.split(/\n{2,}/)) {
if (cur && cur.length + para.length + 2 > max) {
parts.push(cur);
cur = "";
}
cur = cur ? `${cur}\n\n${para}` : para;
while (cur.length > max * 1.4) {
parts.push(cur.slice(0, max));
cur = cur.slice(max);
} // hard cap for huge blocks
}
if (cur) parts.push(cur);
return parts;
}
// ---------- Keyword search: BM25 ----------
const tokenize = (s) =>
s
.toLowerCase()
.normalize("NFKD")
.match(/[a-z0-9]+/g) ?? [];
export class BM25 {
constructor(chunks, k1 = 1.2, b = 0.75) {
this.k1 = k1;
this.b = b;
this.docs = chunks.map((c) => tokenize(c.text));
this.avgLen =
this.docs.reduce((n, d) => n + d.length, 0) / this.docs.length;
this.df = new Map();
for (const d of this.docs)
for (const t of new Set(d)) this.df.set(t, (this.df.get(t) ?? 0) + 1);
}
search(query, k = 10) {
const q = [...new Set(tokenize(query))];
const N = this.docs.length;
const scores = this.docs.map((d) => {
const tf = new Map();
for (const t of d) tf.set(t, (tf.get(t) ?? 0) + 1);
let s = 0;
for (const t of q) {
const f = tf.get(t);
if (!f) continue;
const idf = Math.log(
1 + (N - this.df.get(t) + 0.5) / (this.df.get(t) + 0.5),
);
s +=
(idf * (f * (this.k1 + 1))) /
(f + this.k1 * (1 - this.b + (this.b * d.length) / this.avgLen));
}
return s;
});
return topK(scores, k);
}
}
// ---------- Vector search ----------
export async function embed(texts, kind) {
// embeddinggemma expects task prefixes for queries and documents.
const input = texts.map((t) =>
kind === "query"
? `task: search result | query: ${t}`
: `title: none | text: ${t}`,
);
const res = await fetch(`${OLLAMA}/api/embed`, {
method: "POST",
body: JSON.stringify({ model: "embeddinggemma", input, truncate: true }),
});
if (!res.ok)
throw new Error(`embed failed: ${res.status} ${await res.text()}`);
return (await res.json()).embeddings; // already L2-normalized by Ollama
}
const dot = (a, b) => {
let s = 0;
for (let i = 0; i < a.length; i++) s += a[i] * b[i];
return s;
};
export function vectorSearch(queryVec, chunkVecs, k = 10) {
return topK(
chunkVecs.map((v) => dot(queryVec, v)),
k,
);
}
// ---------- Hybrid: reciprocal rank fusion ----------
export function rrf(rankings, k = 60, limit = 10) {
const score = new Map();
for (const ranking of rankings) {
ranking.forEach((idx, rank) =>
score.set(idx, (score.get(idx) ?? 0) + 1 / (k + rank + 1)),
);
}
return [...score.entries()]
.sort((a, b) => b[1] - a[1])
.slice(0, limit)
.map(([idx]) => idx);
}
function topK(scores, k) {
return scores
.map((s, i) => [s, i])
.sort((a, b) => b[0] - a[0])
.slice(0, k)
.map(([, i]) => i);
}
Notes on the code
- The heading chunker skips code blocks when it looks for headings, so a
#comment in a shell script does not start a new section. - The BM25 class favors clarity over speed. It recounts term frequencies for every query. That is fine for a thousand chunks. In production, use a proper inverted index, such as the full-text search in Postgres, Elasticsearch, or OpenSearch, or the built-in hybrid features of a vector database.
- Vector search is brute force. It compares the query with every chunk. With 1,018 chunks, that is instant. Section 10 explains when you need an index instead.
- I put the heading path into the text itself, and passed
title: none. Using the model’stitlefield for the article title is a reasonable alternative worth testing.
9. Generating Grounded Answers
Retrieval finds the material, and the model writes the answer. The prompt sets the rules.
const prompt =
"Answer the question using only the sources below. Cite sources like [1]. " +
"If the sources do not contain the answer, reply exactly: I don't know based on these sources.\n\n" +
`Sources:\n${context}\n\nQuestion: ${question}`;
The context is the top four chunks from hybrid search, numbered [1] to [4]. I ran it with gemma4:e4b, a 7.5-billion-parameter local model, at temperature 0.
Three real results
First, a good answer. Asked which mix of capabilities lets an AI agent leak private data, the model listed all three parts of the “lethal trifecta” and cited the right section. The answer took 2.6 seconds.
Second, a correct refusal. Asked which Kubernetes operator the author recommends for Postgres, a topic none of the articles cover, the model replied exactly “I don’t know based on these sources.” Retrieval had returned loosely related chunks about Kubernetes secrets, and the model did not invent an answer from them.
Third, a failure worth studying. Asked how long to wait before adopting a new package version, retrieval put the right chunk first. That chunk says “Seven days is a practical default.” The model ignored it and answered from the fourth source with a related but useless sentence about why delays help. Retrieval succeeded and generation failed.
These were the four sources the model received, in order.
- The dependency scanning article’s FAQ entry “What cooldown should I use?”, which contains the answer.
- The same article’s FAQ entry “What should I do first?”
- A section of the passkeys article, retrieved by keyword overlap.
- The dependency scanning section “How each tool supports a delay”, which the model chose to quote.
The answer was in the first source, and the model still preferred a longer, more detailed passage further down.
That last case is why you must evaluate the two stages separately. A single “was the final answer right?” score would blame the wrong component. My evals guide tests this same pipeline with 28 questions, two prompt versions, and three kinds of grader.
Prompt rules that help
- Number the sources and ask for citations, so users and graders can check claims.
- Give an exact refusal phrase. It makes “I don’t know” easy to detect and test.
- Put the sources before the question. Long context followed by the question at the end is a widely recommended layout, and it is what my prompt does.
- Choose the temperature by purpose. I used temperature 0 so the tests were repeatable. Production systems often use a small non-zero temperature for more natural answers. If you do, check citations automatically, as described in my evals guide.
- Keep the number of chunks modest. More context is not always better, because irrelevant chunks distract the model and add cost.
10. Vector Databases
A vector database stores embeddings and finds the nearest ones quickly. For small collections, you do not need one. My test searched 1,018 vectors by brute force in memory, and it was instant.
When you need an index
Brute-force search compares the query with every vector, so its cost grows linearly. At hundreds of thousands or millions of chunks, you need an approximate nearest neighbor (ANN) index. The two common types are these.
- HNSW: A layered graph of neighbors. It is fast and accurate, but it uses more memory.
- IVF: It clusters vectors and searches only the nearest clusters. It uses less memory and is often a little less accurate.
Approximate means the index can occasionally miss the true nearest neighbor in exchange for speed. Measure recall on your own data when you tune index settings.
The main options
| Option | Type | Good fit |
|---|---|---|
| pgvector | Postgres extension | Teams already on Postgres who want vectors next to their data |
| Qdrant | Open source vector database | Dedicated vector search with strong filtering |
| Weaviate, Milvus | Open source vector databases | Large collections and built-in hybrid features |
| Elasticsearch, OpenSearch | Search engines with vectors | Teams that already run them for keyword search |
| Pinecone | Managed service | Teams that want no infrastructure at all |
| Chroma, LanceDB, SQLite add-ons | Embedded libraries | Prototypes, local tools, and small apps |
When I checked on November 30, 2026, the latest pgvector tag was v0.8.7, and Qdrant’s latest release was v1.20.2.
How to choose
Start with what you already operate. If you run Postgres, pgvector keeps vectors, text, and permissions in one database, with one backup and one set of access controls. Move to a dedicated engine when you have measured a real need, such as very large collections, heavy filtering, or strict latency targets.
Whatever you choose, make sure it supports metadata filtering. You will need to restrict searches by tenant, user permissions, document type, or date. Filtering after retrieval is not enough, because it can leave you with zero results from your top k.
11. Reranking and Contextual Retrieval
Two techniques often improve retrieval beyond what I tested.
Reranking
A reranker is a model that reads the question and each candidate chunk together, then scores how well the chunk answers the question. It is more accurate than comparing two separate embeddings, but slower, so you only rerank the top 20 to 100 candidates. Rerankers are available as hosted APIs and as open models. I did not test one here.
The cost is a second model call on every question. Its latency and price grow with the number of candidates and their length, so start with the top 20 to 50 and measure. Reranking pays off most when the right chunk usually appears somewhere in the top 20, but not at the top.
Contextual retrieval
In September 2024, Anthropic published a technique it calls contextual retrieval. Before indexing, a language model writes a short description of where each chunk fits in its document, usually 50 to 100 tokens, and that description is prepended to the chunk. Anthropic reported these reductions in the top-20 retrieval failure rate.
- Contextual embeddings alone: a 35% reduction.
- Contextual embeddings plus contextual BM25: a 49% reduction.
- Both, plus reranking: a 67% reduction.
My heading-path prefix is a cheap, structural version of the same idea. It costs no model calls and works well for structured documents. For messy documents without headings, the model-written context from contextual retrieval is the better tool.
Query rewriting and HyDE
You can also improve the query instead of the documents. Query rewriting asks a model to turn a vague or conversational question into a clearer search query, for example by resolving “it” from earlier in a chat. HyDE, short for hypothetical document embeddings, asks a model to write a short imagined answer, and then searches with the embedding of that answer instead of the question. Both add a model call before retrieval, so test whether they help on your own questions.
Late chunking
Late chunking runs the embedding model over a long stretch of the document first, and then splits the resulting token embeddings into chunks. Each chunk’s vector then carries some context from its neighbors. It needs an embedding model with a long context window and access to token-level outputs, so it is less widely supported.
12. Security and Permissions
Retrieval must respect permissions
If two users may see different documents, permission checks must happen during retrieval, not after. Store access information with each chunk, such as tenant ID, team, or document ACL, and filter every search by the current user’s rights. A model cannot be trusted to withhold a document that it was given.
Documents are untrusted input
Every document in your index can contain text aimed at the model. A wiki page, a support ticket, or an uploaded PDF can say “ignore your instructions and…” This is indirect prompt injection, and RAG is one of its main entry points. Treat retrieved text as data, limit what the model can do with tools, and sanitize its output before you render it. My prompt injection guide covers the defenses in detail.
Embeddings are sensitive too
Research has shown that text can be partly reconstructed from its embeddings. Protect your vector store like the documents themselves, with the same access controls and encryption.
13. Running RAG in Production
- Keep the index fresh. Re-index documents when they change, and delete chunks when documents are deleted. Stale chunks produce confidently wrong answers.
- Version every single component. Record which embedding model, chunking settings, and prompt produced each index. Changing any of them can change results.
- Re-embed after model changes. A new embedding model, a new model version, or a change to the query and document prefixes means a full re-index, so plan for the time and cost. Store the embedding model’s name, version, and prefix scheme with every index, so you never mix vectors by accident.
- Log what was retrieved. For each answer, store the chunk IDs and scores. When an answer is wrong, the log tells you whether retrieval or generation failed.
- Watch the total latency. Embedding the question, searching, reranking, and generating all add up. Cache embeddings for repeated questions.
- Keep an evaluation set. Re-run your retrieval test whenever you change chunking, models, or prompts, and only ship changes that hold up.
14. Common Mistakes
- Using fixed-size chunks by default. In my test, they were the weakest option for vector search by a wide margin.
- Dropping the document title and headings. Chunks lose their subject without them.
- Using vector search only. Keyword search catches exact names, numbers, and codes that embeddings blur.
- Ignoring the embedding model’s prefixes. Many models expect different formats for queries and documents.
- Mixing embedding models in one index. Their vectors are not comparable.
- Filtering permissions after retrieval. Filter during the search, or users may see results they should not.
- Stuffing too many chunks into the prompt. Irrelevant context distracts the model and adds cost.
- Judging RAG only by final answers. Measure retrieval and generation separately.
- Trusting your answer key blindly. My own key had a wrong phrase that made a correct result look like a failure.
- Reaching for a vector database too early. A few thousand chunks fit comfortably in memory or in Postgres.
15. Frequently Asked Questions
What chunk size should I use?
There is no universal number. In my test, structure-aware chunks of up to 1,500 characters, averaging about 800, worked well. Start there, keep sections intact, and test two or three sizes on your own questions.
Three rules of thumb help. Keep chunks well under the embedding model’s input limit, which is 2,048 tokens for the model I used, because longer text is truncated. Preserve logical sections where you can. Re-run your retrieval test every time you change the size.
Is RAG still needed now that context windows hold a million tokens?
For small, stable document sets, often not. Put them in the prompt and use caching. For large, changing, or permission-controlled collections, RAG is still cheaper, faster, and easier to audit than sending everything every time.
Which is better, BM25 or vector search?
Neither is better everywhere. In my test, vectors won with good chunking, and BM25 won with fixed windows. Hybrid search was never worse than the better of the two, so it is the safe default.
Can I run RAG entirely offline?
Yes, you can run it offline. Everything in this article ran locally, with EmbeddingGemma for embeddings and Gemma 4 for answers through Ollama. Quality depends on the models you can run, so test your own questions. My local LLM guide covers the setup.
Do I need a framework such as LangChain or LlamaIndex?
No, you do not. The core pipeline in this article is about 120 lines of code. Frameworks help with document loaders, integrations, and tracing. Use one if it saves you work, but understand the steps it performs for you.
How do I stop the model from making things up?
You cannot stop it completely. You can reduce it with an answer-only-from-sources instruction, an exact refusal phrase, citations, and an evaluation set that includes questions with no answer. In my test, the model refused correctly on unanswerable questions, but it still picked the wrong source once.
16. Conclusion
RAG is a search problem first and a language model problem second. If the right passage is not in the prompt, no model can answer well. If it is there, even a small local model often does a good job.
My tests point to three cheap, high-impact choices. Split documents along their structure. Prefix every chunk with its title and heading path. Combine keyword and vector search with reciprocal rank fusion. Together, those moved the right passage into the top five for every one of my 24 questions.
Then measure, and keep measuring. Check retrieval and generation separately, include questions that have no answer, and check your answer key when something fails. Models and tools change quickly, so treat the specifics here as accurate as of late November 2026.
17. References
Models and tools
- EmbeddingGemma model card
- Ollama: embeddinggemma
- Google: EmbeddingGemma 2 announcement
- Ollama API: generate embeddings
- MTEB leaderboard
Techniques
- Anthropic: Contextual retrieval
- Cormack, Clarke, and Büttcher: Reciprocal Rank Fusion (SIGIR 2009)
- Robertson and Zaragoza: The Probabilistic Relevance Framework, BM25 and Beyond
- Günther et al.: Late Chunking