Skip to main content
This guide demonstrates several document chunking strategies using a compact, self-contained Python implementation. You’ll see how each method behaves on a sample document, learn practical trade-offs, and get CLI examples to reproduce the outputs. These patterns are useful for Retrieval-Augmented Generation (RAG), semantic search, vector indexing, and any pipeline that needs consistent, token-bounded text inputs. What you’ll find here:
  • A reusable DocumentChunker implementation (complete file below).
  • Practical examples and CLI invocations for each chunking strategy.
  • Guidance on combining structural and size-limiting approaches for best results.
  • Links to tokenizers and parsing libraries for production use.
The image shows a Visual Studio Code interface with a file explorer on the left and a Python file named "document_chunker.py" open for editing. A terminal window is open at the bottom with a command prompt in a virtual environment.

Overview of chunking strategies

Below are the key strategies demonstrated by the DocumentChunker class. Each method trades off semantic alignment, chunk size control, and continuity across boundaries. References:

1) Line-by-line chunking

Line-by-line chunking groups a fixed number of lines into each chunk. This method is reliable when records are line-oriented (logs, structured exports), but it has no semantic awareness — chunks can split sentences or paragraphs arbitrarily. Example CLI:
Typical output for a chunk (metadata + five lines):
When to use:
  • When input data maps to fixed-record line blocks.
  • As a low-level primitive combined with semantic grouping.
The image shows a code editor with a document related to testing document chunking, displaying metadata and content descriptions for different chunks. The text includes headings and subheadings, as well as a table of contents.

2) Fixed-size chunking with overlap

Fixed-size chunking splits text into character-range chunks of a fixed length. Overlap preserves context when a semantic unit spans a boundary, which helps retrieval and question-answering tasks. Example CLI:
Sample metadata:
Sample chunk:
When to use:
  • When you must guarantee a maximum chunk size for model input.
  • Use overlap to reduce information loss across chunk boundaries.

3) Sliding-window chunking

Sliding-window chunking creates overlapping windows of a fixed size and advances by a step. Compared to naive fixed-size with overlap, sliding windows are often easier to reason about because overlap is controlled by the step size. Example CLI:
Output metadata examples:
Why it helps:
  • Boundaries (e.g., headings, TOC entries) will appear in multiple chunks, enabling robust retrieval or reranking.

4) Sentence-based chunking

Sentence-based chunking splits text into sentences and groups a fixed number of sentences per chunk. This yields linguistically coherent chunks but depends on accurate sentence splitting. Example CLI (max 3 sentences per chunk):
Sample output:
Caveats:
  • Short sentences produce small chunks; consider grouping more sentences or applying a minimum character or token threshold.
  • For production, swap the simple regex splitter with a robust sentence tokenizer (e.g., spaCy).
The image shows a code editing interface with text related to symbolic example offsets and metadata for chunks of content. It includes labels like "Corridor Drift" and "Maintenance Log," with various sections highlighted or outlined.

5) Paragraph chunking

Paragraph-based chunking groups text at blank-line boundaries. Paragraphs are often good semantic units for many narrative or documentation-style sources. Example CLI:
Notes:
  • This method requires clear paragraph delimiters. Preprocessing is sometimes needed if paragraphs are not separated by blank lines (e.g., in OCR output).

6) Page chunking (useful for PDFs and DOCX)

Page chunking uses page boundaries or approximated line ranges to preserve page-level layout. This is essential when headers, footers, or figures belong to a specific page. Usage notes:
  • The demo includes a 10-page DOCX. The chunker reports pages sequentially.
  • Example metadata for the last page:
When to prefer:
  • Legal, academic, or scanned documents where page context matters.
  • Combine with per-page OCR or page-aware parsing for better fidelity.

7) Section / Heading-based chunking (Markdown example)

Heading-based chunking splits by headings and preserves logical document structure — ideal for manuals, specs, and Markdown content. Example CLI (Markdown headings):
Tips:
  • Adjust the --heading-pattern regex for your document format (e.g., HTML headers, reStructuredText).
  • Use this method first, then apply sentence, paragraph, or token-based limits inside sections.
Typical findings: chunk 51 might correspond to an H2 “Glossary”, chunk 52 to “Sample indices”, etc.

Combining strategies & production tips

There is no one-size-fits-all chunker. Common, practical strategies include:
  • Run heading/section-based splitting first to preserve logical units, then apply token-based or fixed-size chunking within each section to respect model input limits.
  • Use sliding windows or fixed overlap to ensure context continuity across boundaries when retrieval quality matters.
  • Replace the naive token splitter with a production tokenizer: tiktoken for OpenAI models or Hugging Face tokenizers for other models.
Additional resources:
Best practice: combine structural chunking (sections/headings/pages) with size-limiting chunking (token or fixed-size with overlap). This preserves semantics while respecting model input limits.
If you want to experiment, the accompanying repository includes the document_chunker.py file shown above and the sample documents used in these examples.

Watch Video

Practice Lab