RAG on Real Documents: Query Rewriting, Chunking, Metadata and Chroma

Part 4 of a RAG workshop series: rewriting vague questions, chunking documents properly, filtering by metadata, and storing vectors from a PDF in Chroma so they survive a restart.
GenAI
RAG
Workshop
Author
Published

September 21, 2026

RAG workshop series. I prepared these notebooks for the RAG day of AI Innovation & Product Development, a three-day workshop I ran for final-year B.Tech AI & Data Science students.

  1. When to use RAG, and when a long context window is enough
  2. Basic RAG from scratch
  3. Hybrid search: BM25, embeddings and a reranker
  4. RAG on real documents: query rewriting, chunking, metadata and Chroma
  5. Agentic RAG: corrective, adaptive and ReAct

All notebooks: github.com/Zilch123/ai-workshop

Part 3 improved the search itself. This part covers what goes around it: the question going in, the chunks being searched, the filters on top, and where the vectors live. It combines two notebooks from the workshop.

Query rewriting

Users ask vague questions. A rewrite step asks the LLM to turn a question into a short search query before retrieval:

def rewrite_query(question):
    response = client.chat.completions.create(
        model="meta-llama/Llama-3.1-8B-Instruct",
        messages=[
            {"role": "system", "content": (
                "Rewrite the user's question into a concise search query. "
                "Return only the rewritten query. Do not answer the question."
            )},
            {"role": "user", "content": question},
        ],
        max_tokens=100,
        temperature=0.2,
    )
    return response.choices[0].message.content or ""

What it produced in the workshop run:

Original: How can I make my apps talk to each other without waiting?

Rewritten: “Real-time inter-app communication without blocking”

It’s shorter and more technical. It also changed the meaning a little. The user wanted asynchronous communication (a queue), and “real-time” points somewhere else. The quotes in the output would also end up in the search query.

So check rewrites before you trust them. A safer pattern is to search with both the original and the rewritten query and merge the results.

Chunking

Text chunking matters more than which embedding model or reranker you pick.

The LangChain splitter docs are a good overview. The main strategies are:

  1. Fixed size with overlap: each chunk repeats the end of the previous one, so a sentence cut at the edge still appears whole in one of them.
  2. Recursive character splitting: try to split on paragraphs first, then lines, then sentences, then words. Chunks follow the document’s structure where they can.
  3. Sentence window: embed single sentences for precise matching, but give the LLM a few sentences either side.
  4. Semantic chunking: start a new chunk where the meaning shifts, measured with embeddings.

Recursive splitting is the usual default:

from langchain_text_splitters import RecursiveCharacterTextSplitter

splitter = RecursiveCharacterTextSplitter(
    chunk_size=1000,        # max characters per chunk
    chunk_overlap=200,      # repeated between neighbouring chunks
    separators=["\n\n", "\n", ". ", " ", ""],
)
chunks = splitter.split_text(document)

In the workshop we tried it on a short Markdown note about machine learning. It came back as a single 775-character chunk, because the whole note was shorter than chunk_size. That’s worth knowing: the splitter only splits when it has to.

With chunk_size=200 and chunk_overlap=40, the same note splits into 6 chunks, one per section, each 97 to 171 characters. Every chunk starts at a heading, so no section gets cut in half. The overlap shows up as the next heading repeated at the end of each chunk. That’s harmless here, but it’s the kind of detail you only notice by printing your chunks.

Metadata filtering

Most production RAG systems filter before they search. Every chunk carries structured fields:

document page chapter year department type
aws_guide.pdf 24 Amazon SQS 2025 Engineering Documentation
hr_policy.pdf 5 Leave Policy 2025 HR Policy
finance_report.pdf 8 Revenue 2025 Finance Report

An HR question then only searches HR documents from this year:

metadata_filter = {"department": "HR", "year": 2025}

This does two jobs. It cuts out irrelevant chunks that happen to score well, and it’s how you enforce permissions: a user only searches documents they’re allowed to see.

In the first notebook I defined this filter and left using it as an exercise. In-memory lists don’t make it easy. A vector database does.

From a Python list to Chroma

Every notebook so far kept embeddings in a NumPy array. Restart the runtime and they’re gone. That’s fine for 4 paragraphs and not fine for a 10,000-page manual.

Chroma is an embedded vector database. There’s no server and no account. It’s just a folder on disk that survives a restart.

Step 1: a real PDF

We wrote the AWS knowledge base out as aws_guide.pdf, one service per page, with fpdf2, then read it back with pypdf. The rest of the code works on any PDF, so students could upload their own.

from pypdf import PdfReader

reader = PdfReader("aws_guide.pdf")

Step 2: chunk per page and keep the page number

splitter = RecursiveCharacterTextSplitter(chunk_size=400, chunk_overlap=50)

pdf_chunks, pdf_metadatas = [], []
for page_number, page in enumerate(reader.pages, start=1):
    for chunk in splitter.split_text(page.extract_text()):
        pdf_chunks.append(chunk)
        pdf_metadatas.append({"page": page_number, "source": "aws_guide.pdf"})

Splitting page by page means every chunk knows where it came from. That page number becomes both a filter and a citation.

Step 3: store in Chroma

We pass in the same all-MiniLM-L6-v2 model as an embedding function, so the vectors match the rest of the series:

import chromadb
from chromadb import EmbeddingFunction

class SentenceTransformerEmbeddingFunction(EmbeddingFunction):
    def __call__(self, input):
        return embedding_model.encode(input).tolist()

chroma_client = chromadb.PersistentClient(path="./chroma_db")
collection = chroma_client.get_or_create_collection(
    name="aws_guide",
    embedding_function=SentenceTransformerEmbeddingFunction(),
)
collection.add(
    ids=[f"chunk-{i}" for i in range(len(pdf_chunks))],
    documents=pdf_chunks,
    metadatas=pdf_metadatas,
)

Step 4: prove it persists

A new client pointing at the same folder finds everything, without calling encode() again:

reconnected = chromadb.PersistentClient(path="./chroma_db").get_collection(
    name="aws_guide",
    embedding_function=SentenceTransformerEmbeddingFunction(),
)
reconnected.count()

Step 5: the metadata filter, for real

where= restricts the search to matching chunks. Here, only page 2 (SQS):

collection.query(
    query_texts=["How do applications communicate without waiting for each other?"],
    n_results=3,
    where={"page": 2},
)

Step 6: answer with citations

The prompt now labels each chunk with its page and asks the model to cite it:

context = "\n\n".join(f"(page {m['page']}) {text}" for text, m in retrieved)

prompt = f"""
Answer the question using only the context below. Cite the page number.

CONTEXT:
{context}

QUESTION:
{question}
"""

A cited answer is easy to check: open the page and read it. That’s one of the main reasons to build RAG at all (see Part 1).

Stretch tasks

For students who finished early:

  • Bring your own PDF and see whether retrieval holds up on a document the examples weren’t written for.
  • Add BM25 on top of Chroma. Pull the chunks with collection.get(), build a BM25 index, and fuse the scores as in Part 3.

What’s next

Every pipeline so far runs in a fixed order: retrieve, then answer, once. Part 5 turns retrieval into a loop with decisions: check whether the results are any good, decide whether to search at all, and let the model search again.

Notebooks: