Retrieval-augmented generation, or RAG, is the most common pattern in enterprise AI. Give a model a question, search your own documents for relevant passages, and let it answer from what it finds. The idea fits on a napkin. The first prototype takes an afternoon.
Then it meets real documents. Answers cite the wrong version of a policy. Tables come back as word soup. A question about “the Acme renewal” returns three paragraphs about a different Acme. Someone asks why the assistant knew about a reorganization that has not been announced.
None of these are model problems. They are data problems, and they have data engineering answers. The teams that succeed with RAG stop treating it as a prompt with a search box and start treating it as what it is: a pipeline that extracts, transforms and loads knowledge, with quality checks at every stage.
Stage one: parsing is where quality is won or lost
Everything downstream depends on turning source files into clean text with structure intact. This is harder than it looks.
- PDFs carry no reliable reading order. Two-column layouts get merged line by line. Headers and footers repeat on every page and pollute every chunk.
- Tables lose their meaning when flattened. “Region / Q3 / Q4” followed by forty numbers is useless to a model unless each value stays attached to its row and column.
- Scanned documents need optical character recognition, and its errors are silent.
- Slides and spreadsheets hold meaning in position and formatting, not just text.
The practical answer is a layout-aware parser for complex documents, with tables converted to a structured form such as Markdown or JSON, and page furniture stripped out. Keep the document’s own structure (title, section headings, page numbers) as metadata. You will need it later.
A useful test: take twenty representative documents, parse them, and have a person read the output. If they cannot follow it, neither can the model.
Stage two: chunking is a design decision
Documents are split into chunks before they are indexed, because search returns passages, not whole files. The default in most tutorials is a fixed size, such as 500 tokens with some overlap. It is a reasonable start and a poor finish.
Fixed-size chunks cut sentences in half, separate a heading from the paragraph it introduces, and split a table from its caption. Better approaches follow the document:
- Structure-aware chunking splits on headings, sections and list boundaries, so each chunk is a coherent unit.
- Context headers prepend each chunk with where it came from: “Travel Policy 2026 > International travel > Approval limits.” A chunk that says “the limit is $5,000” means nothing on its own. With its header, it is an answer.
- Parent-child retrieval indexes small chunks for precise matching but returns the larger section around them, so the model sees enough context to answer well.
There is no universal chunk size. Contracts, support tickets and engineering runbooks behave differently. Treat chunking parameters as configuration, version them, and choose them with measurements rather than intuition.
Stage three: metadata is half of retrieval
Every chunk should carry metadata: source system, document type, owner, effective date, version, business unit, region and, critically, who is allowed to see it.
Metadata does three jobs.
- Filtering. “What is our parental leave policy in Germany?” should search only current HR policies for Germany. A filter does that precisely; semantic search alone will happily return the US policy, because it is about the same thing.
- Freshness. When two versions of a document exist, the effective date decides which one wins.
- Permissions. Covered below, and the part most teams get wrong.
If your source systems do not hold this metadata cleanly, RAG will expose the gap. That is often the most valuable finding of an early project.
Stage four: use more than one kind of search
Vector search, which compares meaning through embeddings, is excellent at matching paraphrases. Ask about “time off after having a baby” and it finds the parental leave policy without either word in common.
It is weak at exact terms: product codes, contract numbers, error messages, people’s names, acronyms specific to your business. Classic keyword search (BM25 and its relatives) is strong precisely there.
Hybrid search runs both and merges the results, commonly with a method called reciprocal rank fusion that rewards documents ranking well in either list. On enterprise content, hybrid search beats either method alone in nearly every evaluation we have run. It is now supported by most vector databases and search engines, so there is little reason to skip it.
Then rerank. A cross-encoder reranker reads the question and each candidate passage together and scores how well they match. It is slower than the first search, so you run it on the top 30 to 50 results, and keep the best handful. Reranking usually brings the largest single quality improvement after hybrid search, and it lets you send the model less text, which lowers cost.
Stage five: keep it current, incrementally
A RAG index is a copy of your knowledge, and copies go stale. The question is how fast, and whether anyone notices.
Re-indexing everything each night works for small collections and fails for large ones. The pattern that scales is the same one data engineers use for any replicated data: change data capture. Most document systems expose change feeds (SharePoint and OneDrive through Microsoft Graph delta queries, for example, and similar mechanisms in Google Drive, Confluence and most databases). Process only what changed: new documents are parsed and indexed, edited ones are re-chunked and replaced, deleted ones are removed.
Deletion is the case teams forget. A document removed from SharePoint but still in the index is still answering questions.
Also version your embeddings. When you change the embedding model, every vector must be regenerated, because vectors from different models are not comparable. Plan for a parallel index and a cutover, not an in-place update.
Stage six: enforce permissions at query time
In the prototype, everyone sees everything. In production, the assistant must never answer from a document the person asking could not open themselves.
There are two broad approaches.
- Separate indexes per audience. Simple and safe for a few clearly separated groups, such as HR-only content. It does not scale to thousands of documents with individual permissions.
- Permission filtering on every query. Each chunk stores the groups allowed to read its source document. At query time, you look up the user’s groups and filter the search to those chunks before ranking. Filtering after retrieval is weaker: if the top fifty results are all restricted, the user gets nothing useful, and leaked snippets can slip through logs and traces.
Either way, permissions must stay in sync with the source. When someone leaves a project team, their access to its documents should end in the index as quickly as it ends in SharePoint. This is a pipeline job, and it needs monitoring like one.
Stage seven: measure retrieval and generation separately
When a RAG answer is wrong, there are two very different causes. Either search did not find the right passage, or it found it and the model used it badly. You cannot fix what you cannot tell apart.
So measure both:
- Retrieval: for a set of real questions, do the right passages appear in the results? Context recall (did we find what was needed?) and context precision (how much of what we found was relevant?) are the standard measures.
- Generation: given the passages, is the answer faithful to them, and does it actually answer the question? Faithfulness, the share of claims in the answer supported by the sources, is the measure that catches hallucination.
Open-source frameworks such as Ragas implement these metrics, often using a model as the judge. Use them, but check the judge against human grades on a sample before you trust it.
The foundation is a golden set: a few hundred real questions, collected from users and subject experts, each with the documents that should be found and the facts a good answer must contain. Run it on every change: new chunking, new embedding model, new prompt, new model version. If a change does not move the numbers, it is not an improvement. If it lowers them, it does not ship.
A failure taxonomy worth adopting
When a reviewer marks an answer wrong, record why. Over time, a simple taxonomy tells you where to invest:
- Not in the corpus. The answer does not exist in any indexed document. A content gap, not a technical one.
- Not retrieved. The answer exists but search missed it. Look at chunking, metadata filters and hybrid search.
- Retrieved but ranked low. It was in the top fifty but not the top five. Look at the reranker.
- Retrieved but ignored. The model had it and answered from elsewhere. Look at the prompt and the amount of context.
- Stale or wrong version. Look at freshness and version metadata.
- Should not have been visible. A permission defect. Treat it as a security incident.
In the first months of most programs, the first two categories dominate. That is good news, because they are fixed with ordinary data engineering.
Who should build it
RAG projects are usually staffed as AI projects, with prompt engineers and application developers. The work that decides their success is parsing, modeling, incremental loading, access control and data quality. Those are data platform skills.
That is why we treat a company’s data platform as its AI strategy. The organizations that already run clean, governed, well-documented data pipelines find RAG straightforward. The ones that do not discover, through their assistant, exactly where their knowledge is messy.