Splitting by Headings
Markdown sections.
Our pages have headings, like change of mind, and faulty items. Headings are the writer's own idea of where one topic ends and the next begins. A markdown splitter cuts at the headings, and remembers them.

- Writers add headings
- Natural topic breaks
- Split at headings
Markdown header splitter
We tell the splitter which heading levels to watch. One hash is the title, two hashes is a section. Each piece it returns keeps its headings as metadata. Run it. Three sections, each labelled with the page title, and its own section name.
from pathlib import Path
from langchain_text_splitters import MarkdownHeaderTextSplitter
splitter = MarkdownHeaderTextSplitter(headers_to_split_on=[("#", "title"), ("##", "section")])
text = Path("data/rag/northwind/returns.md").read_text()
for piece in splitter.split_text(text):
print(piece.metadata)
print(" ", piece.page_content[:60]){'title': 'Returns and refunds', 'section': 'Change of mind'}
You can return any unused item within 30 days of delivery fo
{'title': 'Returns and refunds', 'section': 'Faulty items'}
If an item is faulty, you can return it at any time within t
{'title': 'Returns and refunds', 'section': 'Refund timing'}
Refunds go back to the original payment method within 7 workWhen to use it
Heading splits work beautifully for well structured documents, like help pages, manuals, and wikis. Sections can still be long, so we often split again, with the recursive splitter, inside each section.
| key | value |
|---|---|
| Great for | help pages, manuals |
| Keeps | heading metadata |
| Long sections | split again |
| Combine | headings + recursive |
Summary
The markdown splitter cuts at headings, and stores them as metadata. Combine it with recursive splitting for long sections. Next, choosing a chunk size.
Key takeaways- Split at # and ##
- Headings as metadata
- Then recursive