Sub topic 8
Respecting document structure: headings, code, and tables
This chapter assumes you can read Python and know what an embedding is. It also assumes you have seen fixed-size and recursive splitting from earlier chapters. Those splitters treat a document as a flat string. Real documents have headings, code blocks, and tables, and a splitter that ignores them produces chunks that are hard to retrieve and hard to read.
Why flat splitting fails
A fixed-size splitter counts characters or words and cuts wherever the count runs out. That causes three common failures:
- A heading ends up at the bottom of one chunk while its body starts the next, so the body loses its topic.
- A code block is cut in half. Neither half is runnable, and the function name may sit in the other chunk.
- A table is cut between rows. The second chunk holds numbers with no column headers.
Structure-aware chunking uses the document's own markers as boundaries. It keeps units that belong together in one chunk and records where each chunk came from.
Splitting on headings
Markdown headings give natural section boundaries. The splitter below starts a new section at each heading and keeps the heading path, such as ["Install", "Linux"], as metadata. It also tracks whether it is inside a fenced code block, so a # comment in a code sample is not mistaken for a heading.
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
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 sectionsA section can still exceed your size limit. In that case, run a recursive splitter on the section body and copy the same headings value onto every piece.
Keeping code blocks whole
Treat a fenced code block as an atomic unit. If it fits the limit, keep it together with the sentence that introduces it. If it is larger than the limit, split it at blank lines or at function boundaries, not mid-statement. Accept a slightly oversized chunk before you accept a broken one. An embedding model sees a half-function as noise.
Splitting tables by row
A large table must be cut by rows, and every piece must repeat the header rows. Without the header, a chunk containing 42 | 3.1 means nothing.
def split_table(table, max_rows=20):
lines = table.strip().splitlines()
header, rows = lines[:2], lines[2:]
pieces = []
for i in range(0, len(rows), max_rows):
pieces.append("\n".join(header + rows[i:i + max_rows]))
return pieces or [table]This assumes a Markdown table, where the first two lines are the header and the separator. For HTML, apply the same idea with <thead> and <tr> elements. For very wide tables, you can also convert each row to a sentence such as "Plan: Pro, Price: 20, Seats: 5", which embeds better than pipe characters.
Common errors
| Error | Symptom | Fix |
|---|---|---|
| Treating `#` in code as a heading | Sections named after shell comments | Track fenced blocks, as above |
| Dropping the heading path | Chunks that are ambiguous out of context | Store `headings` and prepend it to the text you embed |
| Tiny sections | Many chunks of one or two lines | Merge neighbors under the same parent heading until a minimum size |
| Table rows without a header | Numbers with no meaning | Repeat the header in each piece |
Merging small sections
Heading-based splitting can create many very short chunks. Short chunks give weak embeddings and fill the top-k results with near-duplicates. After splitting, merge adjacent sections that share a parent heading until the combined text reaches a minimum size, such as 100 tokens.
Exercise
A document has a 60-row Markdown table, and your chunk limit allows about 20 rows. Describe how you would chunk it, and why each piece must start with the header rows.
Show answer
Split the table body into three groups of 20 rows. Prepend the header row and separator row to each group, giving three self-contained tables. Each chunk then keeps its column names, so a row value can be interpreted and embedded with the right meaning. Without the header, the second and third chunks would hold unlabeled numbers.