Parent Documents
Find small, read big.
Small chunks are great for matching, because each holds one idea. But the model often needs more around them to answer well. Parent documents give us both. We search small chunks, then hand the model the larger page they came from.

- Small chunks match well
- Models need more
- Search small, read big
Small chunk, big parent
We split into very small chunks, just one hundred and twenty characters. Search finds the best small chunk. Then we look up the full page it came from, by its source. Run it. A tiny chunk matched, and the model gets the whole returns page.
from rag_kit import load_docs, make_chunks, Index
docs = load_docs()
index = Index(make_chunks(docs, size=120, overlap=0))
score, hit = index.search("How long do refunds take?", 1)[0]
parent = next(d for d in docs if d["source"] == hit["source"])
print("matched:", hit["text"])
print("parent: ", parent["source"], "with", len(parent["text"]), "characters")matched: Refunds go back to the original payment method within 7 working days of the item reaching our warehouse. parent: returns.md with 641 characters
Also uses rag_kit.py
import warnings; warnings.filterwarnings("ignore")
from pathlib import Path
import numpy as np
from sentence_transformers import SentenceTransformer
import faiss # after torch, so the two libraries load safely together
faiss.omp_set_num_threads(1)
from langchain_text_splitters import RecursiveCharacterTextSplitter
def load_docs(folder="data/rag/northwind"):
return [{"source": p.name, "text": p.read_text()} for p in sorted(Path(folder).glob("*.md"))]
def make_chunks(docs, size=300, overlap=50):
splitter = RecursiveCharacterTextSplitter(chunk_size=size, chunk_overlap=overlap)
return [{"source": d["source"], "text": t.replace("\n", " ")}
for d in docs for t in splitter.split_text(d["text"])]
embedder = SentenceTransformer("all-MiniLM-L6-v2", device="cpu")
def embed(texts):
return embedder.encode(texts, normalize_embeddings=True)
class Index:
def __init__(self, chunks):
self.chunks = chunks
self.vectors = embed([c["text"] for c in chunks])
def search(self, query, k=3):
scores = self.vectors @ embed([query])[0]
top = np.argsort(-scores)[:k]
return [(round(float(scores[i]), 2), self.chunks[i]) for i in top]Choosing the parent
The parent can be the whole page, or just the section around the chunk. Whole pages are simple, but can be long. Sections are a good middle ground. LangChain's parent document retriever does this for you.
| key | value |
|---|---|
| Whole page | simple, long |
| Section | middle ground |
| Child chunks | small, for search |
| LangChain | ParentDocumentRetriever |
Summary
Search small chunks for precision, then give the model the bigger parent for context. Next, chunk headers.
Key takeaways- Small for search
- Big for reading
- Linked by source