Simple definition#
- Chunking is splitting documents into smaller passages so that search can return just the relevant part, and so it fits in the prompt.
- An embedding is a list of numbers (a vector) that represents the meaning of a piece of text. Texts with similar meaning have vectors that are close together.
Together they decide what your RAG system can find.
Embeddings, simply#
flowchart LR
A["'How do I reset my password?'"] --> EM["Embedding model"]
B["'I forgot my login credentials'"] --> EM
C["'Quarterly revenue grew 8%'"] --> EM
EM --> VA["[0.12, -0.48, 0.33, ...]"]
EM --> VB["[0.10, -0.45, 0.31, ...]"]
EM --> VC["[-0.71, 0.22, -0.05, ...]"]
VA <-->|"close: similar meaning"| VB
VA <-->|"far"| VC
The first two sentences share no keywords, yet their vectors are close — this is semantic search, and why RAG finds answers phrased differently from the question.
Similarity metrics#
| Metric | Idea | Notes |
|---|---|---|
| Cosine similarity | Angle between vectors (1 = same direction) | The default for text |
| Dot product | Cosine × lengths | Equal to cosine when vectors are normalised; fastest |
| Euclidean (L2) distance | Straight-line distance | Lower = more similar |
Use the metric the embedding model was trained for (its documentation says).
Choosing an embedding model#
| Factor | Consideration |
|---|---|
| Retrieval quality | Check the MTEB leaderboard retrieval scores, then test on your data |
| Language | Multilingual model if documents or users are not English-only |
| Domain | Code, legal or medical text may benefit from specialised or fine-tuned models |
| Dimensions | 384–3,072 typical. More dimensions → more storage and slower search |
| Max input length | Must exceed your chunk size |
| Hosting | API (OpenAI, Cohere, Voyage, Google, Amazon Titan) or open-weight (BGE, E5, GTE, Nomic) |
| Cost | Embedding is cheap per token but the whole corpus is embedded, and re-embedded on model change |
Matryoshka embeddings can be truncated (for example from 3,072 to 512 dimensions) with modest quality loss, trading accuracy for storage and speed.
Why chunk at all?#
- Precision — a 40-page PDF embedded as one vector blurs dozens of topics into one point; a question about one paragraph will not match it well.
- Context budget — you want to send the 5 most relevant paragraphs, not 5 whole documents.
- Model limits — embedding models have a maximum input length.
Too small is also bad: a chunk with one sentence lacks the context to be understood (“It must be approved by a director” — what must?).
Chunking strategies#
flowchart TB
F["Fixed-size<br/>every N tokens + overlap"] --> R["Recursive<br/>split on paragraphs → sentences → words<br/>until under size"]
R --> S["Structure-aware<br/>split on headings, sections,<br/>Markdown/HTML elements, code functions"]
S --> SE["Semantic<br/>split where meaning changes<br/>embedding similarity between sentences"]
SE --> PC["Hierarchical / parent-child<br/>search small chunks, return big parent"]
| Strategy | How | Pros | Cons |
|---|---|---|---|
| Fixed-size + overlap | 500 tokens, 50–100 overlap | Simple, predictable | Cuts mid-sentence and mid-topic |
| Recursive character/token | Try \n\n, then \n, then . , … |
Respects paragraphs; good default | Ignores document structure |
| Structure-aware | Split by headings, list items, tables, code blocks | Chunks match the author’s topics; headings become metadata | Needs good parsing per format |
| Semantic | Break where adjacent sentences’ embeddings diverge | Coherent topics | Slower; variable sizes |
| Parent-child (small-to-big) | Index small child chunks; return their larger parent section | Precise matching and rich context | More storage and logic |
| Sentence window | Index sentences; return sentence ± neighbours | Very precise retrieval | Many vectors |
| Late chunking | Embed the whole long document with a long-context model, then pool token vectors per chunk | Each chunk’s vector carries document context | Needs a suitable model |
| Contextual chunk headers | Prepend document title and section path, or an LLM-written summary, to each chunk before embedding | Big quality gains for little effort | Extra tokens; LLM cost if summarised |
Parent-child retrieval#
flowchart LR
Q["Query"] --> V["Search child chunks<br/>~150 tokens each"]
V --> H["Best child: §4.3 sentence<br/>about business class"]
H --> P["Look up parent<br/>whole §4 Air Travel, ~1,200 tokens"]
P --> LLM["Send parent to LLM"]
Practical starting point#
- Structure-aware or recursive chunking, ~300–800 tokens, 10–20% overlap.
- Prepend the document title and section heading path to every chunk (“Travel Policy 2026 > Air travel > Business class”).
- Keep tables whole where possible; convert them to Markdown or describe each row.
- Store rich metadata: source, URL, section, page, date, version, language, ACL.
- Then measure retrieval recall on your evaluation set and tune size, overlap and strategy.
Parsing: the hidden half of quality#
| Content | Challenge | Approach |
|---|---|---|
| Native PDFs | Columns, headers/footers, hyphenation | Layout-aware parsers; strip boilerplate |
| Scanned PDFs | No text layer | OCR, or a vision-capable model |
| Tables | Row/column meaning lost when flattened | Extract as Markdown/HTML; keep whole; or one chunk per row with headers |
| Slides | Fragmented text, meaning in images | Combine slide title + text + speaker notes; describe diagrams with a vision model |
| Web/Confluence | Navigation, cookie banners | Extract main content; keep heading hierarchy |
| Code | Functions and classes | Split by syntax (AST), not by characters |
Tools include Apache Tika, PDF-specific readers, Unstructured, Docling and cloud document AI services; Spring AI has document readers for PDF, Tika, Markdown, JSON and more.
Common mistakes#
Review questions#
What is an embedding? A dense vector representing the meaning of text, produced by an embedding model. Similar meanings map to nearby vectors, which enables semantic search with cosine similarity or dot product.
How do you choose chunk size? Start from the document’s natural structure, typically 300–800 tokens with 10–20% overlap, include heading context, then tune on an evaluation set measuring retrieval recall and answer quality. Smaller chunks give precise matching; larger ones give more context; parent-child retrieval gets both.
What is parent-child (small-to-big) retrieval? Index small chunks for precise matching, but return their larger parent section to the LLM so it has enough context to answer.
What happens if you change the embedding model? All existing vectors become incompatible. You must re-embed the corpus, typically into a new index, validate retrieval quality, and switch over.
How do you handle tables in RAG? Parse them into structured text (Markdown/HTML), keep them whole or chunk by row with headers repeated, add a short description, and test retrieval with table-specific questions. For numeric analysis, consider querying the source data with SQL tools instead.
Summary#
- Embeddings place meaning in vector space; similar texts are close.
- Chunk to one topic per chunk, with headings and metadata; ~300–800 tokens is a typical start.
- Structure-aware, semantic, parent-child and contextual headers improve retrieval.
- Parsing quality (tables, scans, layout) often matters more than the chunking algorithm.
- Version embedding models; switching requires re-indexing.
References#
- Muennighoff et al., MTEB: Massive Text Embedding Benchmark, 2022.
- Kusupati et al., Matryoshka Representation Learning, 2022.
- Günther et al., Late Chunking: Contextual Chunk Embeddings Using Long-Context Embedding Models, 2024.
- Anthropic, Introducing Contextual Retrieval, 2024.