Chunking by Structure: Headings, Paragraphs and Markdown

JS
Jai Singh
24 Nov, 2026 4 min read 8 views

Structure-based chunking uses the boundaries that authors already wrote: headings, paragraphs, list items and code blocks. Chunks built this way are more coherent than fixed-size windows, because each one tends to cover a single topic. When your documents have headings, such as Markdown, HTML or wiki pages, this is usually the best default.

Why structure beats a fixed window

A writer starts a new section when the topic changes. A fixed window ignores that and cuts wherever the counter runs out, so the end of one topic and the start of the next end up in the same vector. That mixed vector matches neither topic well. Splitting at headings keeps topics apart and gives you a free label for every chunk: the heading itself.

Step 1: split Markdown by headings

The function below walks through a Markdown string line by line. It tracks the current heading path (for example "Billing > Refunds") and starts a new section whenever it meets a new heading. It ignores lines that look like headings inside fenced code blocks, which is a common bug.

import re

def split_markdown(text: str):
    sections = []
    path = []                 # [(level, title), ...]
    body = []
    in_code = False

    def flush():
        content = "\n".join(body).strip()
        if content:
            sections.append({
                "heading_path": " > ".join(t for _, t in path),
                "text": content,
            })
        body.clear()

    for line in text.splitlines():
        if line.strip().startswith("```"):
            in_code = not in_code
        m = None if in_code else re.match(r"^(#{1,6})\s+(.*)$", line)
        if m:
            flush()
            level, title = len(m.group(1)), m.group(2).strip()
            while path and path[-1][0] >= level:
                path.pop()
            path.append((level, title))
        else:
            body.append(line)
    flush()
    return sections

Each returned section has a heading_path and the text under it. The path is valuable: a paragraph that says "Run the migration twice" means much more with "Upgrading > Version 3" above it.

Step 2: split long sections into paragraphs

Some sections are long. Pack paragraphs into chunks up to a size limit, never cutting inside a paragraph. If a single paragraph is still too long, fall back to sentence splitting, as shown in the previous post.

def pack_paragraphs(text: str, max_words: int = 250) -> list[str]:
    paragraphs = [p.strip() for p in re.split(r"\n\s*\n", text) if p.strip()]
    chunks, current, count = [], [], 0
    for p in paragraphs:
        n = len(p.split())
        if current and count + n > max_words:
            chunks.append("\n\n".join(current))
            current, count = [], 0
        current.append(p)
        count += n
    if current:
        chunks.append("\n\n".join(current))
    return chunks

def chunk_markdown(text: str, doc_title: str, max_words: int = 250):
    out = []
    for sec in split_markdown(text):
        for piece in pack_paragraphs(sec["text"], max_words):
            out.append({
                "heading_path": sec["heading_path"],
                "text": piece,
                "embed_text": f"{doc_title} > {sec['heading_path']}\n\n{piece}",
            })
    return out

Notice the embed_text field. It prepends the document title and heading path to the text that you send to the embedding model. This gives the vector the context that the paragraph alone lacks. You can still show the original text to the user. We build on this idea in a later post about contextual headers.

Handling other formats

  • HTML. Parse with a library and treat h1 to h6 as headings. Convert to Markdown first if that is easier.
  • Word and Google Docs. Export to Markdown or HTML to keep heading styles.
  • Slides. Treat each slide as a section, with the slide title as the heading.
  • FAQs. One question and answer per chunk is almost always right.
  • Chat transcripts. Group by conversation turns or time windows, not by headings.

Edge cases

  • Tiny sections. A heading with one line under it makes a weak chunk. Merge very short sections into the previous or next one, or into their parent.
  • Headings with no hierarchy. Some pages bold text instead of using real heading tags. A light check for short bold lines may be needed.
  • Code blocks. Never split in the middle of one. Treat a fenced block as an unbreakable unit unless it exceeds your limit.
  • Tables. Keep a table together with its caption or lead-in sentence when you can.

Try it

Run chunk_markdown on one of your real documents and print each chunk with its heading path. If chunks read like complete thoughts and the paths look right, your structure splitting works. If many chunks are one or two lines, merge small sections. If some are huge, lower max_words or check that the document really has headings.

Structure-aware splitting keeps meaning intact, which makes both retrieval and the final answer better. Combine it with a size cap and you have a strong default for most documentation-style content.

Was this article helpful?

Comments

No comments yet. Have a question or a tip? Be the first to share it.

Leave a comment

Comments are reviewed before they appear.