AI Hints
Home›RAG Tutorial›Smarter Splitting
RAG · Lesson 20 of 120

Splitting by Headings

Markdown sections.

⏱ 2 min read▶ Video at 19:46🎓 Free
Watch this lesson in the RAG courseWatch on YouTube ↗Full RAG course

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.

Splitting by Headings
From the video: Splitting by Headings
  • 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.

by_headings.pypython
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])
Output
{'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 work

When 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.

keyvalue
Great forhelp pages, manuals
Keepsheading metadata
Long sectionssplit again
Combineheadings + 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
Next up: Choosing a Chunk Size — not too big, not too small