Module 2 · Parsing & chunking

Splitting strategies: sentence, semantic, hierarchical

5 min read

Chunking decides what the system will be able to retrieve. A passage that's too long dilutes the information: its vector represents an average of several topics, and it fills the context with useless text. A passage that's too short loses context: "3 years" doesn't say of what. A passage cut in the wrong place separates a rule from its exception. LlamaIndex offers several strategies; none is universal, and the best systems combine them.

By size: SentenceSplitter

The basic strategy splits text into chunks of a target size (in tokens), trying never to cut mid-sentence, with an overlap between consecutive chunks:

from llama_index.core.node_parser import SentenceSplitter

splitter = SentenceSplitter(chunk_size=512, chunk_overlap=64)
nodes = splitter.get_nodes_from_documents(documents)
ParameterEffectOrder of magnitude
chunk_sizeMaximum size of a node, in tokens256 to 1024
chunk_overlapTokens repeated between two consecutive nodes10 to 15% of the size

Overlap limits losses at boundaries: a sentence straddling two chunks stays readable in at least one of them. Watch one detail: metadata counts toward the size. The splitter reserves room for the metadata that will be included in the node's text; with a lot of metadata and a small chunk size, it raises an error ("Metadata length is longer than chunk size").

By structure: MarkdownNodeParser

A well-structured document says where to cut it: its headings. The MarkdownNodeParser creates one node per section, and records the heading path in the header_path metadata:

[structure] /Politique de retours et remboursements/ → ## Délai de rétractation
[structure] /Politique de retours et remboursements/ → ## Conditions de retour

Each node then matches a unit of meaning, and the heading path gives the passage its context. That's why Lumen's pipeline chains structure-based splitting first, then size-based splitting, which only re-splits sections that are too long. It's also a strong argument for LlamaParse: a PDF converted into structured Markdown splits as well as a native Markdown file.

By meaning: SemanticSplitterNodeParser

Semantic chunking places boundaries where the topic changes. It computes the embedding of each sentence (or small group of sentences), measures the distance between consecutive sentences, and cuts at the largest gaps:

from llama_index.core.node_parser import SemanticSplitterNodeParser

splitter = SemanticSplitterNodeParser.from_defaults(
    embed_model=embed_model,
    buffer_size=1,                         # sentences grouped to smooth the comparison
    breakpoint_percentile_threshold=95,    # cuts at the 5% largest gaps
)

Useful for long, weakly structured texts (minutes, transcripts, articles), it has two costs: one embedding per sentence at ingestion, and chunks of unpredictable size (some very long). Combine it with a SentenceSplitter to bound the size.

Hierarchical: small to search, large to answer

The size dilemma has an elegant solution: index small chunks, precise for retrieval, but give the model the large chunk that contains them. The HierarchicalNodeParser splits each document at several scales, keeping parent-child links:

from llama_index.core.node_parser import HierarchicalNodeParser, get_leaf_nodes
from llama_index.core.retrievers import AutoMergingRetriever

parser = HierarchicalNodeParser.from_defaults(chunk_sizes=[512, 256, 96])
nodes = parser.get_nodes_from_documents(documents)
leaves = get_leaf_nodes(nodes)                       # only the smallest are embedded

storage_context = StorageContext.from_defaults()
storage_context.docstore.add_documents(nodes)        # every level is kept in the docstore
index = VectorStoreIndex(leaves, storage_context=storage_context)

retriever = AutoMergingRetriever(
    index.as_retriever(similarity_top_k=6), storage_context, simple_ratio_thresh=0.3
)

When enough "leaves" of the same parent are retrieved (here, 30%), the AutoMergingRetriever replaces them with their parent: the model receives the whole section rather than scattered fragments. On Nimbus policies, a question about return fees thus brings back two complete sections instead of six fragments.

Sentence window: retrieve a sentence, read the paragraph

A variant of the same principle, the SentenceWindowNodeParser creates one node per sentence, and stores the window of neighboring sentences as metadata. At retrieval, you find the most relevant sentence, then a post-processor replaces it with its window:

from llama_index.core.node_parser import SentenceWindowNodeParser
from llama_index.core.postprocessor import MetadataReplacementPostProcessor

parser = SentenceWindowNodeParser.from_defaults(window_size=2)   # 2 sentences before, 2 after
postprocessor = MetadataReplacementPostProcessor(target_metadata_key="window")

Very precise for pinpoint factual questions, it multiplies the number of nodes (one per sentence) and therefore the size of the index.

Choosing a strategy

CorpusStarting strategy
Structured documentation (Markdown, HTML, PDF parsed to Markdown)Structure, then size — Lumen's choice
Long, weakly structured textsSemantic, bounded by size
Precise questions on long documentsHierarchical with auto-merging
Pinpoint facts in dense proseSentence window
FAQs, short sheets, ticketsOne document = one node, no splitting

The right setting can't be guessed: it's measured. Build a set of representative questions (lesson 5.3), then compare strategies and sizes on retrieval hit rate. A change in chunk size can move that rate by tens of points.

Key takeaways

  • Too long dilutes, too short decontextualizes, badly placed separates a rule from its exception.
  • SentenceSplitter: target size and overlap; metadata counts toward the size.
  • MarkdownNodeParser splits by section and keeps the heading path: apply it before size-based splitting.
  • Semantic for weakly structured texts; hierarchical or sentence window to search small and answer large.
  • The right strategy is measured on your questions, not on intuition.

Practice

  1. Run examples/01_documents_nodes.py and compare the nodes produced by size and by structure for the returns policy.
  2. Build a hierarchical index on the policies and compare, for "Quels sont les frais en cas de rétractation ?", the passages returned with and without AutoMergingRetriever.
  3. Vary chunk_size (128, 512, 1024) and measure the hit rate with examples/06_evaluation.py (with real embeddings).

Resources