Chunking Strategies for Knowledge Bases and Better RAG Retrieval
This article explains why chunking is the foundational problem in Retrieval-Augmented Generation (RAG) and how it determines retrieval quality. It covers the core trade-offs between granularity, completeness, and cost, then walks through common strategies—fixed-length, recursive structure-based, document-structure-aware, semantic similarity, and Q&A or summary augmentation—along with practical configuration parameters and tuning heuristics. You will also learn how hierarchical parent-child chunking and metadata filtering improve precision, how to handle tables, code, and multimodal content, and how to build an evaluation set to iterate on chunking with data instead of intuition. A checklist of common mistakes is included to help you avoid frequent pitfalls.
1. Why Chunking Is the First-Order Problem in RAG
Retrieval-Augmented Generation (RAG) chains “retrieve first, then generate” into a single pipeline: the user’s question is encoded into vectors or keywords, the most relevant fragments are located in the knowledge base, and those fragments are passed to the LLM as context to produce an answer. The ceiling of this chain is largely determined at the chunking stage. If the chunks are semantically incomplete after splitting, no amount of stronger embedding models or higher retrieval counts will help—you are only patching errors on top of the wrong material.
Poor chunking quality typically shows up as three types of failures. First, semantic fragmentation: a complete conclusion is split across two chunks, and retrieval only hits one half. Second, topic mixing: a single chunk is stuffed with multiple unrelated topics, so its vector representation gets “averaged out,” making it both hard to retrieve accurately and hard to rank highly. Third, missing context: a chunk is detached from its title, section, and preconditions, so the model cannot see the applicable scope and can only answer by guessing. Understanding these three failure modes is the starting point for designing a chunking strategy.
2. The Core Trade-Off: Granularity, Completeness, and Cost
Chunking is essentially a trade-off among three conflicting goals.
- Small granularity: vector semantics are concentrated and similarity computation is sharper, but each chunk carries too little information. You need to retrieve more chunks to assemble an answer, prompting costs rise, and the model is more easily distracted by noise.
- Large granularity: context is complete, but the vector is diluted across multiple topics, retrieval precision drops, and chunks can easily exceed the usable budget of the model’s context window.
- Completeness constraints: structures such as code blocks, tables, formulas, clause numbers, and step lists become nearly impossible to recover semantically once they are cut.
The common engineering practice is to treat semantic boundaries as the first priority, a maximum length as a hard constraint, and an overlap window as the buffer between the two. In other words, first find the “natural place to cut,” then check whether it exceeds the length limit, and finally use a small overlap to preserve cross-chunk references and continuity.
3. Common Chunking Strategies and When to Use Them
3.1 Fixed-Length Splitting
Hard-split by character count or token count. This is the simplest to implement and suits loosely formatted plain text that lacks structure. The drawback is that it cuts sentences and paragraphs, so it generally needs to be paired with an overlap window.
3.2 Recursive Structure-Based Splitting
Split level by level in a hierarchy of “paragraph → sentence → word,” breaking at the higher level first and recursing to the next level only when a chunk is too long. This is the safest default strategy for most documents.
3.3 Document-Structure-Aware Splitting
Use heading levels, numbering schemes, list items, and code fences as split points so that each chunk naturally corresponds to a subsection. Technical documentation, policies and standards, and product manuals are especially well suited to a variant of this approach: use the subsection as the splitting unit, then perform a secondary split on subsections that are too long.
3.4 Semantic Similarity Splitting
Compute the vector similarity between adjacent sentences or paragraphs and break where similarity shows a clear dip, making the topic within each chunk more consistent. This usually works better, but requires extra encoding overhead and threshold tuning.
3.5 Q&A Pairs and Summary Augmentation
Pre-rewrite long documents into “question–answer” pairs or generate summary chunks, and store them alongside the original chunks. This can significantly improve hit rates for conversational questions, at the cost of higher build-stage expense.
4. Practical Parameter Configuration
The following parameters are a general starting point and should be tuned against your own corpus:
chunk_config = {"splitter": "recursive", # recursive structure splitting, preferred default"chunk_size": 500, # measured in tokens; 300~800 for technical docs"overlap": 50, # about 10%~20% of chunk_size"separators": ["\n## ", "\n### ", "\n\n", "。", ";", "\n", " "],"keep_structure": True, # keep code blocks and tables from being cut"attach_metadata": True # attach title path, document source, version, etc.}
Three rules of thumb for tuning: if retrieval results “look relevant but don’t answer fully,” increase chunk size or raise the retrieval count first; if you “retrieve a pile of plausible-looking but wrong content,” shrink the chunks and strengthen metadata filtering first; if answers frequently contain unclear references, increase the overlap window first.
5. Hierarchical Chunking and Metadata: The Key Levers for Precision
Flat chunks at a single granularity can rarely satisfy both “retrieve comprehensively” and “rank accurately.” A more mature approach is to build a parent-child hierarchy: child chunks are used for vector retrieval, and once a hit occurs, you trace back to the parent chunk (a subsection or full section) as the context sent to the model. This preserves the retrieval sharpness of small granularity while restoring the semantic completeness of large granularity.
Metadata is another underrated lever. Storing the title path, document type, applicable version, effective time, and permission tags alongside each chunk lets the retrieval stage perform structured filtering before similarity ranking, which can greatly reduce wrong hits across versions and product lines. An example:
{"text": "After authentication is enabled, all external interfaces must carry a valid credential...","metadata": {"title_path": "Security Configuration > Interface Authentication","doc_type": "Operations Manual","version": "v3.2","acl": "internal"}}
6. Handling Tables, Code, and Multimodal Content
Tables are best split by row or by logical block, with the header repeated in each chunk; otherwise, cells detached from the header have almost no meaning. Code should be split along function or class boundaries, preserving the file path it belongs to and dependency notes. Images and scanned documents can first be converted to text via OCR and then enter the unified chunking pipeline, while retaining original position information for traceback.
7. Evaluation: Driving Chunking Iteration with Data
Chunking should not be finalized by intuition; it needs a quantifiable feedback loop. Build an evaluation set containing real questions and standard answer chunks, and track three metrics: hit rate (whether the standard chunk enters the retrieval results), context precision (the proportion of retrieved chunks that are actually useful), and end-to-end answer accuracy. Change only one variable at a time—for example, adjust only chunk length or only the overlap ratio—observe the direction in which the metrics move, and gradually converge on a configuration suited to your own corpus.
In related practice at Baidu AI Cloud, knowledge base solutions typically package document parsing, splitting, vectorization, and retrieval orchestration into a configurable pipeline, so developers only need to focus on chunking granularity, metadata design, and evaluation set construction; at the underlying layer, object storage can hold the original documents, a message queue can decouple build tasks, and logging services with monitoring and alerting can track fluctuations in retrieval quality.
8. Common Mistakes Checklist
- Blindly pursuing small chunks, leading to insufficient context and an exploding retrieval count;
- Ignoring the overlap window, so all cross-chunk references are lost;
- Skipping metadata filtering, allowing multi-version documents to contaminate each other;
- Using the same set of parameters for all document types, mixing policies, manuals, and code;
- Lacking an evaluation set, so every adjustment is made by feel with no way to regression-test.
Chunking is the highest return-on-investment optimization point in RAG. First get the semantic boundaries and hierarchical structure right, then use metadata to narrow the retrieval scope, and finally use an evaluation set to continuously calibrate parameters—retrieval quality and answer reliability will improve together.
