Sub topic 8
Respecting document structure: headings, code, and tables
This chapter assumes you know basic Python, what an embedding is, and how the fixed-size and recursive splitters from the previous chapters work. Those splitters see text as a stream of characters. Real documents are not streams. They have headings that scope the text below them, code that breaks when cut in half, and tables whose rows mean nothing without the header. Structure-aware chunking uses those features as boundaries.
Why character-based splitters fall short
A recursive splitter that prefers paragraph breaks does reasonably well on prose. On structured documents it fails in predictable ways:
- A heading lands at the end of one chunk and its body starts the next. The chunk with the body no longer says what it is about.
- A fenced code block is cut in the middle. Neither half is runnable, and the half without the opening fence looks like prose.
- A table is cut between rows. The second chunk holds numbers with no column names.
- A list item such as "Step 4: restart it" ends up in a chunk without the steps that explain what "it" is.
Each failure lowers retrieval quality. The embedding of a broken fragment is vague, so it ranks poorly for the question it should answer. When it does get retrieved, the model has to guess what it means. Structure-aware chunking fixes this by choosing boundaries from the document's own markup.
Heading-based splitting
Most technical documents are trees. A ## section sits inside a # section, and the section title describes everything under it. The usual approach is to start a new section at each heading and record the heading path, the chain of ancestor titles, as metadata.
Here is the splitter from the plan. It keeps a stack of headings and flushes the buffered lines whenever a new heading appears.
import re
def split_markdown(text):
sections, path, buf = [], [], []
def flush():
body = "\n".join(buf).strip()
if body:
sections.append({"headings": list(path), "text": body})
buf.clear()
for line in text.splitlines():
m = re.match(r"^(#{1,6})\s+(.*)$", line)
if m:
flush()
level = len(m.group(1))
path[:] = path[:level - 1]
path.append(m.group(2).strip())
else:
buf.append(line)
flush()
return sectionsThe line path[:] = path[:level - 1] keeps only the ancestors of the new heading. When a ## heading follows another ##, the old sibling is dropped. When a # heading appears, the whole path resets.
This version has a bug: it treats every line that starts with # as a heading, including comment lines inside fenced code blocks. A shell snippet containing # install dependencies would create a bogus section.
Keeping code blocks intact
The fix is to track whether you are inside a fence and to skip heading detection while you are. Code blocks should also be kept whole when you pack and re-split sections.
The code below builds the fence marker from characters so the example can be shown inside a Markdown chapter. In your own code you can write the three backticks directly.
import re
FENCE = "`" * 3
def split_markdown(text):
sections, path, buf = [], [], []
in_code = False
def flush():
body = "\n".join(buf).strip()
if body:
sections.append({"headings": list(path), "text": body})
buf.clear()
for line in text.splitlines():
if line.lstrip().startswith(FENCE):
in_code = not in_code
buf.append(line)
continue
m = None if in_code else re.match(r"^(#{1,6})\s+(.*)$", line)
if m:
flush()
level = len(m.group(1))
path[:] = path[:level - 1]
path.append(m.group(2).strip())
else:
buf.append(line)
flush()
return sections
doc = "\n".join([
"# Guide",
"Intro text.",
"## Install",
"Run the setup.",
FENCE + "bash",
"# install deps",
"pip install foo",
FENCE,
"## Usage",
"Call run().",
])
for s in split_markdown(doc):
print(" > ".join(s["headings"]))Running this prints three section paths:
Guide
Guide > Install
Guide > UsageThe # install deps comment stays inside the Install section because the fence toggle switched heading detection off.
This is a simplification. A real Markdown fence can use tildes, can be indented, and closes only with a marker at least as long as the opening one. For production use, parse with a Markdown library such as markdown-it-py and read the token stream, which handles these cases correctly.
What to do with sections that are too big
A heading-based split gives you sections of uneven size. A short "Overview" might be 40 tokens. A long "Configuration" section might be 4,000, which exceeds many embedding input limits and dilutes the vector. Treat the structure split as the first pass, then handle size:
- Split by headings.
- If a section is under your maximum size, keep it as one chunk.
- If it is over, split it with the recursive splitter, using the section's heading path for every piece.
- Optionally merge tiny neighboring sections under the same parent so you do not index many near-empty chunks.
The following diagram shows that flow.
When you split a large section, do not break inside a code block if you can avoid it. A simple rule is to treat each fenced block as an atomic unit during packing. Allow it to exceed the size limit by some margin, for example 1.5 times, before you split it. If it still does not fit, split at blank lines or function boundaries, and repeat the opening line (such as the language tag) and a short comment saying the block continues.
Chunking tables
A table is a set of rows that share a header. The header gives each cell its meaning. A chunk that contains rows 12 to 20 but not the header is hard to interpret. Hard to retrieve too: a question about "monthly price for the Pro plan" matches the header words, not the bare numbers.
There are three common options:
- Keep the table whole when it fits in the size limit. This is the best choice for small tables.
- Split by rows and repeat the header in every chunk. This suits long tables with independent rows.
- Convert each row to a sentence or key-value text, such as "Plan: Pro; Price: 20 USD per month; Seats: 5". This works well when rows are looked up individually and the table has few columns, but it multiplies the amount of text you store.
The function below implements the second option for a Markdown table.
def split_table(table_text, max_chars=800):
lines = table_text.strip().splitlines()
if len(lines) < 3:
return [table_text.strip()]
header, rows = lines[:2], lines[2:]
base = "\n".join(header)
chunks, current, size = [], [], len(base)
for row in rows:
if current and size + len(row) + 1 > max_chars:
chunks.append("\n".join(header + current))
current, size = [], len(base)
current.append(row)
size += len(row) + 1
if current:
chunks.append("\n".join(header + current))
return chunksThe first two lines are the header row and the separator row, and both go into every chunk. A single row longer than max_chars still becomes its own chunk. That is acceptable because it keeps the row whole.
Tables outside Markdown need different handling. For HTML, parse the <table> element and reuse the same idea with <thead> and <tbody>. For PDFs, the hard part is extracting the table at all, since text extraction often flattens it into a stream of cells. Check extraction output before tuning chunk sizes.
Other structures worth respecting
- Lists. Keep a list with its introducing sentence ("To reset the device:"). A numbered procedure usually should not be split unless it is very long.
- HTML. Use the tag hierarchy (
h1toh6,section,article) the way you use Markdown headings. Remove navigation, footers, and cookie banners before chunking, since they add noise that matches many queries. - Source code. Split at function and class boundaries, using a parser such as tree-sitter or Python's
astmodule, instead of by line count. Store the file path and symbol name as metadata. - Q&A and FAQ pages. Keep each question with its answer as one chunk.
Gotchas
- Heading text is not always informative. Titles like "Notes" or "Details" say little. The full path ("Billing > Refunds > Notes") is more useful than the last title alone.
- Depth of the heading you split on. Splitting on every level can produce many tiny chunks. Splitting only on
#and##gives bigger ones. Choose the level by looking at the size distribution of your sections, not by default. - Repeating headings in chunk text. If the heading path is only stored as metadata, the embedding model never sees it. Prepending it to the chunk text before embedding often improves retrieval. The next chapter covers this in detail.
- Inconsistent source formatting. Documents converted from Word or PDF often use bold text instead of real headings. A heading-based splitter will treat the whole file as one section. Inspect a few documents before you trust the splitter.
Summary of the approach
Use document markup as the primary boundary, then apply a size limit as a second pass. Keep code blocks and tables whole where possible, repeat table headers when you must split, and record the heading path with every chunk. Then compare this approach with a plain recursive splitter on your own questions, using the recall@k measurement introduced later in this tutorial.
Exercise
A Markdown file has a bash code block containing the line "# build the image". Your heading-based splitter checks each line with the regular expression for lines starting with one to six "#" characters followed by whitespace. What goes wrong, and how do you fix it? Then, a 60-row pricing table is split into three chunks by row count with no other handling. Which problem appears in chunks two and three, and what is the fix?
Show answer
The comment line matches the heading pattern, so the splitter starts a new section in the middle of the code block and adds a fake heading ("build the image") to the path. The code is cut in two. The fix is to track a fence state, toggling it on each line that starts with the fence marker, and to skip heading detection while inside a fence (or use a Markdown parser that already knows about code blocks). For the table, chunks two and three have no header row, so their cells have no column names and match queries poorly. The fix is to repeat the header and separator rows at the top of every chunk, as split_table does, or to convert each row into self-describing key-value text.