Sub topic 10
Small chunks for search, larger parents for context
This chapter assumes you can write basic Python and know what an embedding is. It also assumes you know how top-k vector search works and have seen fixed-size or recursive chunking from earlier chapters. You should also know what a token is.
The tension that parent-child retrieval resolves
Chunk size pulls in two directions.
- Small chunks produce focused embeddings. A 60-word chunk about one refund rule matches a question about refunds sharply. Small chunks also leave little irrelevant text to dilute the match.
- Large chunks carry the context a model needs to answer. The sentence "It expires after thirty days" is useless unless the reader can see what "it" refers to.
With one chunk size, you pick a compromise. Parent-child retrieval, also called small-to-big retrieval, uses two sizes. You embed and search small child chunks. When a child matches, you return the larger parent section it came from.
- A child is a small chunk, usually 50 to 150 tokens. It is embedded and searched.
- A parent is the larger unit that contains the child. It can be a section, a page, or a fixed window of 300 to 1,500 tokens. It is stored and returned to the generator, but usually not embedded.
Each child records the ID of its parent. At query time, search finds children, and a lookup swaps them for parents.
What each side is optimized for
| Property | Child chunks | Parent chunks |
|---|---|---|
| Purpose | Matching the query | Giving the model context |
| Typical size | 50 to 150 tokens | 300 to 1,500 tokens |
| Embedded | Yes | Usually no |
| Stored in | Vector index | Key-value store or database |
| Main failure if too large | Diluted embeddings, weaker matches | Wasted context budget, noise |
| Main failure if too small | Fragments with no standalone meaning | Missing surrounding explanation |
This split also helps with the embedding input limit. Embedding models have a maximum input length, and the children always fit under it. Parents can be sized for your generation context budget instead.
Implementation
The code below has two parts. The first builds parents and children from a document. The second searches children and returns deduplicated parents. It uses a toy bag-of-words embedding so it runs with no dependencies. In a real system, replace embed and the linear scan with an embedding model and a vector index.
import math
from collections import Counter
def make_parents_and_children(doc_id, text, parent_size=300,
child_size=60, child_overlap=10):
if child_overlap >= child_size:
raise ValueError("child_overlap must be smaller than child_size")
words = text.split()
step = child_size - child_overlap
parents, children = {}, []
for p_start in range(0, len(words), parent_size):
parent_words = words[p_start:p_start + parent_size]
parent_id = f"{doc_id}:p{p_start // parent_size}"
parents[parent_id] = " ".join(parent_words)
for c_start in range(0, len(parent_words), step):
piece = parent_words[c_start:c_start + child_size]
children.append({
"id": f"{parent_id}:c{c_start // step}",
"parent_id": parent_id,
"text": " ".join(piece),
})
if c_start + child_size >= len(parent_words):
break
return parents, children
def embed(text):
return Counter(w.strip(".,;:!?()").lower() for w in text.split())
def cosine(a, b):
dot = sum(v * b.get(k, 0) for k, v in a.items())
na = math.sqrt(sum(v * v for v in a.values()))
nb = math.sqrt(sum(v * v for v in b.values()))
return dot / (na * nb) if na and nb else 0.0
def retrieve_parents(query, parents, children, k_children=6, k_parents=3):
q = embed(query)
scored = sorted(
((cosine(q, embed(c["text"])), c) for c in children),
key=lambda pair: pair[0],
reverse=True,
)[:k_children]
best = {}
for score, child in scored:
if score > 0 and child["parent_id"] not in best:
best[child["parent_id"]] = score
top = list(best.items())[:k_parents]
return [(pid, score, parents[pid]) for pid, score in top]
if __name__ == "__main__":
filler = "filler " * 100
sentence = "The refund window is thirty days after delivery. "
text = filler + sentence + filler
parents, children = make_parents_and_children(
"manual", text, parent_size=50, child_size=20, child_overlap=5
)
for pid, score, body in retrieve_parents("refund window days",
parents, children):
print(pid, len(body.split()))Running the demo prints manual:p2 50. The 208-word document splits into parents of up to 50 words. The refund sentence sits at words 100 to 107, so it falls in parent manual:p2, which spans words 100 to 149. Only the first child of that parent contains the query terms. Every other child scores zero and is dropped by the score > 0 check.
Several details in the code matter in practice.
- Children never cross parent boundaries. Each parent is split on its own. This keeps the child-to-parent mapping unambiguous, so every child has exactly one parent.
- Deduplication keeps the best score. Several children from one parent often match together. The dictionary keeps the first, and therefore highest-scoring, occurrence and preserves rank order.
- Search more children than you return parents.
k_childrenis larger thank_parentsbecause several children collapse into one parent. If you fetch only 3 children, you may end up with 1 parent.
Choosing parents
The parent definition matters more than the child definition, because parents are what the model reads. There are three common options.
- Fixed windows. Split the document into equal blocks of, say, 400 words, as above. This is simple, but a parent can start or end mid-thought. Use a recursive splitter for the parent level to avoid this.
- Structural units. Use sections, pages, or heading blocks as parents. Parents are then coherent units, but their sizes vary. A 5,000-token section as a parent can overflow your budget, so cap the size and split large sections.
- Sliding context window. Skip separate parents. Store children in document order, and when one matches, return it plus its neighbors, for example two before and two after. This is sometimes called sentence-window retrieval. It needs no parent store, only
doc_idand a position on each child. Windows from nearby matches overlap, so merge them before sending them to the model.
For structured documents, option 2 combines well with the heading-aware splitting from the structure-aware chapter. Children are chunks inside a section, and the parent is the section.
Sizing guidance
There is no universal setting, but these starting points are reasonable.
- Start children at 100 tokens or fewer for fact lookup, and 150 to 250 for explanatory prose. Make sure each child is long enough to stand alone as a sentence or two.
- Make parents 3 to 10 times the size of children. A 1:2 ratio gives little benefit. A 1:50 ratio floods the model with unrelated text.
- Multiply parent size by
k_parentsto get the worst-case context cost. Three parents of 1,000 tokens is 3,000 tokens before the question, instructions, and answer. - Keep child overlap modest, around 10 to 20 percent. The parent already supplies surrounding context, so overlap matters less than in single-level chunking.
Failure modes and edge cases
Context budget overruns. Parents are big. If the top parents together exceed your budget, you must truncate or drop some. Count tokens with the generator's tokenizer, not with word counts, and drop the lowest-ranked parents first.
Duplicate and overlapping parents. With fixed-window parents, deduplication by ID is enough. With sliding windows, two matches from the same page give overlapping text. Merge overlapping ranges, or the model sees the same sentences twice.
Ranking loses precision. Scoring happens on children but the model receives parents. If a parent has three children, one strong match and two weak ones, it ranks by its best child. That is usually right, but a long parent with one lucky child match can outrank a short, fully relevant one. Some systems rerank the parents with a cross-encoder before generation.
One parent can hide the answer. A large parent adds noise, and models can miss details in the middle of long contexts. If answer quality drops as parents grow, shrink them rather than adding more.
Stale links. Children point to parents by ID. When you re-chunk or update a document, rebuild both stores together. A child that points to a missing or changed parent returns wrong text or errors. Version the IDs or replace both stores atomically.
Extra storage and complexity. You maintain two stores and a mapping, and indexing produces more vectors than a single-level index of parent-sized chunks. For a small, clean corpus of short documents, this cost is not worth it.
When to use it
Use parent-child retrieval when:
- queries are specific but the answers need surrounding explanation, as in manuals, legal text, and technical documentation;
- single-size chunking forces a choice between missed matches (large chunks) and unreadable results (small chunks);
- evaluation shows that the right document is found but the retrieved text is too thin to answer from.
Skip it when documents are already short and self-contained, such as FAQ entries, product records, or tickets. There, each document is its own parent and child.
Measuring whether it helps
Do not adopt it on intuition. Run the same test questions through both setups and compare. Retrieval-level metrics such as recall@k can compare configurations as long as you define a hit consistently. For parent-child, map each retrieved child to its parent ID before computing the metric, and label relevant items by parent ID too.
def recall_at_k(retrieved_ids, relevant_ids, k=5):
if not relevant_ids:
return 0.0
hits = len(set(retrieved_ids[:k]) & set(relevant_ids))
return hits / len(relevant_ids)Recall@k on parent IDs tells you whether the right section reached the generator. It does not tell you whether the generator used it correctly. Also read a sample of the final answers. A configuration with higher recall but much larger parents may produce worse answers.
Exercise
In retrieve_parents, you set k_children=3 and k_parents=3, and your queries often return only one parent. Why does this happen, and what is the simplest fix?
Show answer
Several of the top three children come from the same parent, so deduplication collapses them into one or two parents. The simplest fix is to retrieve more children than parents you want, for example k_children=10 with k_parents=3. That gives deduplication enough candidates to find three distinct parents.
Exercise
A corpus of 150-word FAQ answers is indexed with 60-word children and 300-word parents. Evaluation shows recall@5 on parent IDs is no better than single-level chunking, and the context is larger. What should you conclude and do?
Show answer
Each FAQ answer already fits in one chunk and stands alone, so the parent adds no new context, only extra text. Drop the two-level design and index each answer as one chunk, which gives the same recall at lower cost and complexity.