Chunking documents with internal structure
medium 7 minA structured document encodes meaning in relationships.
Video lesson · Chapter 1 of 4
The price between two headings
Theory
Read or listen first. About 2 min.
What it is
A structured document encodes meaning in relationships. A table cell inherits its row and column headers; a function belongs to a module; a figure belongs to a caption and page. Splitting must retain those relationships in both text and provenance.
Why it exists
Run a reconstruction test. Hand someone only the retrieved unit and ask which entity, quantity and source it describes. If those facts cannot be recovered, preserve more structure or retrieve the parent record.
Which column owns the value 19.95?
Inside this chapter
Chapter sources- HTML & Markdown Chunking
- HTML and Markdown expose hierarchy through headings, lists, tables and code fences. Preserve the heading path and keep a table header with its rows. A generic character split can put “price per month” in one chunk and its numbers in another, leaving the retrieved amounts ambiguous.
Markup gives you free structure: heading levels define a tree, lists keep items together, tables have a header row and code fences mark verbatim blocks. Split along that tree, carry the heading path (for example
Pricing > Business plans) into each chunk, and never cut inside a code fence. When a table is too large, split by rows and repeat the header in every piece.Example. Split a Markdown table after row ten. Repeat the header in the second chunk so “19.95” remains associated with its billing period.
Repeat the header when a table is split
Chunk Header row Rows Can you read 19.95? Chunk 1 Plan · Monthly · Annual Rows 1-10 Yes Chunk 2, no header none Rows 11-20: Plan K · 19.95 · 199 No, which column? Chunk 2, header repeated Plan · Monthly · Annual Rows 11-20 Yes, monthly - Code Chunking
- Code search benefits from boundaries around functions, methods and classes. Keep the symbol name, file path and relevant signature so retrieved fragments remain interpretable. Very large functions still need subchunks. Keep source spans so a reader can inspect the surrounding implementation.
Code has an exact grammar, so use it: a parser (for example a syntax tree library) can find function and class boundaries reliably. Each chunk should carry its qualified symbol name, file path, signature and line span. Very long functions still need subchunks, each repeating the signature. Imports and class fields often matter for understanding a method, so consider a short header with them.
Example. Retrieve one method named reset from two classes. Include module and class names so the two implementations can be distinguished.
Another example. A coding assistant answers "where do we retry failed payments?". Retrieving a bare
for attempt in range(3)loop is useless; retrievingpayments/worker.py::charge_with_retrylines 40-72 lets the agent open the file and edit the right place.Two methods called reset
Without the qualified name both chunks look like one function. - JSON Chunking
- Split nested JSON along object or record boundaries. Carry the parent key and a stable path with each child. Flattening two customers’ address objects into standalone city strings loses ownership. Retain enough structure to reconstruct a cited record and to apply filtering before retrieval.
Split nested data at record boundaries (one order, one customer) rather than at arbitrary characters. Each child keeps a stable path from the root so the system knows who owns a value and can rebuild the record for citation. Keep filterable keys such as tenant or status as metadata so they can restrict search before ranking.
Example. Two records have a city field. A source path such as orders/17/shipping/city preserves ownership that the flat token “Boston” would lose.
Flat values versus paths
Flattened token With path Owner recoverable? Boston orders/17/shipping/city = Boston Yes, order 17 Boston customers/4/billing/city = Boston Yes, customer 4 19.95 orders/17/items/2/price = 19.95 Yes, item 2 of order 17 A path is cheap to store and makes filters and citations possible. - PDF & Document Chunking
- PDF pages have visual layouts that may not correspond to text order. Identify columns, headings and repeated furniture. Preserve page coordinates, table structure and links to the original scan. Test whether a retrieved line still has its correct label when displayed out of the page layout.
PDF extraction is layout analysis. A good pipeline finds columns, headings, tables and repeated headers or footers before producing text. Running heads like "Company confidential, page 4" appear on every page and pollute retrieval if kept. Store bounding boxes so the interface can highlight the cited region and so a human can check a suspicious number in seconds.
Example. Find the annual price on page four of a brochure. Compare the extracted cell, its header and its bounding box with the original page.
From page pixels to a usable chunk - 1Page 4 layoutdetect columns and regions
- 2Drop furnitureheaders, footers, page numbers
- 3Rebuild tablecells with row and column labels
- 4Attach coordinatespage 4, bounding box
- 5Chunk + scan linktext plus original region
Coordinates let a reviewer open the exact spot on the page.
- Multimodal Chunking
- In multimodal chunking, associate figures with captions and surrounding paragraphs while keeping the original media addressable. Text and image representations may require different encoders and budgets. A successful match to a caption does not establish that the system correctly read values from the figure.
A figure has three parts that belong together: the image, its caption, and the paragraph that discusses it. Index them as one unit with links back to the original media. Matching a caption only proves the unit is relevant; reading a value off the chart needs either a model that looks at the image or extracted data, and the answer should say which it used.
Example. A chart caption says revenue rose, while the y-axis shows the increase is one percent. Retain both the figure and caption to answer “by how much?”
Keep the figure, caption and paragraph linked
- Image & OCR Chunking
- OCR converts image regions to text with imperfect recognition. Retain the image reference, bounding box and uncertainty where available. A single digit error can materially change an answer. Route low-confidence numeric fields to review or image-based verification before citing them as facts.
OCR engines usually return a confidence per word or character along with its box. Keep both. Numbers deserve extra checks because one wrong digit changes meaning: validate format (a currency field should have two decimals), cross-check totals where possible, and re-read low-confidence regions with a different method. Never let an unverified OCR value become a cited fact.
Example. OCR reads 8.50 as 850. Reopen the bounded image region before converting the extracted value into a claim about a charge.
Another example. An invoice extractor reads a total of 1,250.00 while the line items add up to 125.00. The mismatch rule flags the invoice, and a re-read of the cropped total region shows the comma was a smudge.
Route low-confidence numbers to a second look
A missing decimal point turns 8.50 into 850.
How it works
Step through the idea, or press Play.
Price table. Monthly · Annual
Understand it
Worked example
Which column owns the value 19.95?
- 1
Monthly · Annual
Reading order and repeated headers matter. On a scanned page two amounts can sit next to each other with no repeated currency or period label.
- 2
Monthly = 19.95
Bind row name, column label, currency, page number and bounding box to the cell. Retain an image reference for checking OCR.
- 3
Plan B · monthly · page 4
The evidence is now interpretable outside the original page. Apply the same idea to a code symbol, JSON path or Markdown heading.
Follow the handoffs
What the structured chunk must carry
| Field | Value | Why it matters |
|---|---|---|
| Row | Plan B | Which product |
| Column | Monthly | Which billing period |
| Currency | USD | Which unit |
| Value | 19.95 | The fact itself |
| Page and box | p4 · (312, 540, 368, 556) | Check against the scan |
Can support an annual-price claim
- Chunk has column header Annual
- Header and value share one table region
- Box checked against the page
Cannot
- Value exact but header missing
- Header guessed from neighbouring chunk
- OCR confidence low on the header
Summary
The whole topic in one minute.
Extraction accuracy and semantic ownership are separate. The same number can support the wrong claim if its period or column is lost.
Run a reconstruction test. Hand someone only the retrieved unit and ask which entity, quantity and source it describes. If those facts cannot be recovered, preserve more structure or retrieve the parent record.