Chunking Strategies and Practical Guide to Building a RAG Knowledge Base
This guide explains how chunking determines the upper limit of RAG performance and walks through building a knowledge base end to end. It covers the roles of embedding and rerank models, four common chunking patterns, preparation and configuration steps, and recall testing for iteration, along with common pitfalls and limitations to help you choose and tune a chunking strategy for your own corpus.
Chunking Strategies and Practical Guide to Building a RAG Knowledge Base
1. Why Chunking Sets the Upper Limit of RAG Quality
In a Retrieval-Augmented Generation (RAG) system, the retrieval module finds the fragments most relevant to a question from private corpora, and the generation module composes an answer from those fragments. Generation quality is capped by retrieval quality, and retrieval quality depends largely on how the corpus was split into fragments.
Chunking is essentially about turning long documents into retrieval units that are semantically self-contained and appropriately sized. When the granularity is too coarse, a single chunk covers multiple topics, its vector representation gets “averaged out,” the semantic focus blurs, irrelevant content interferes with retrieval, and the context window is consumed unnecessarily. When the granularity is too fine, chunks lose context: pronouns, references, and preconditions are cut off, the model sees isolated sentences, and answers can easily be taken out of context.
Chunking is therefore not an incidental preprocessing step but a core design decision for the knowledge base, one that must be weighed together with document structure, question distribution, and the model’s context length.
2. Two Essential Model Concepts
2.1 Embedding Models
An embedding model maps text to a fixed-dimensional dense vector so that semantically similar texts sit closer together in vector space. At retrieval time, the user’s question is encoded the same way, and approximate nearest neighbor search returns candidate chunks. Three points matter when choosing a model: its Chinese semantic representation ability, whether its maximum input length matches the chunk length, and the relationship between vector dimension and storage and retrieval cost. Note that the same corpus must be encoded with the same embedding model; switching models means rebuilding the entire index.
2.2 Rerank Models
Vector retrieval uses a “dual-tower” structure: the question and the documents are encoded independently, which is fast but offers shallow interaction. A rerank model uses a “cross” structure, concatenating the question and each candidate chunk for joint encoding, which captures fine-grained relevance at the cost of higher latency. A common engineering approach is two-stage: vector retrieval recalls 20–50 candidates, then the rerank model narrows them to the top 3–5 for the generation stage. This “coarse recall plus fine ranking” combination is one of the most cost-effective ways to improve answer hit rate.
3. The Full Knowledge Base Build Workflow
3.1 Preparation: Collecting and Organizing Material
Start by defining the knowledge boundary. Material in a personal learning scenario is usually a mix of textbooks, lecture notes, personal notes, and exam questions, in formats ranging from plain text and rich text to tables and scanned images. Three organizing principles apply: normalize everything to UTF-8; remove repeated noise such as headers, footers, and table-of-contents page numbers; and run OCR on scanned content before ingestion, with manual spot checks on recognition quality. The noisier the material, the higher the tuning cost for chunking and retrieval later.
3.2 Design: Choosing a Chunking Strategy
Common chunking patterns fall into four categories:
- Fixed-length splitting: split by character or token count, with an optional overlap region to preserve cross-chunk context. Simple to implement, but it can cut sentences and semantic units.
- Structure-based splitting: split on document structure boundaries such as heading levels, paragraphs, and lists. This gives the best semantic completeness, provided the document structure is well-formed.
- Semantic splitting: detect semantic drift between adjacent sentences via vector similarity and determine boundaries adaptively. Effective but computationally expensive.
- Q&A-style splitting: rewrite content into question–answer pairs. This fits Q&A retrieval best but adds generation cost.
Selection guidance: prefer structure-based splitting for well-structured documents; use fixed-length splitting with 10%–20% overlap for messy plain text; and layer semantic splitting or Q&A rewriting on top of core material that demands high accuracy.
Optimization tips: prefix each chunk with its section heading to compensate for missing context; keep the header row for tabular content and split it into independent chunks row by row; avoid breaking code and formulas across chunks; and keep chunk length within the embedding model’s input limit.
Illustrative configuration logic:
def split_by_structure(doc):chunks = []for section in doc.sections: # traverse by heading levelbody = section.text.strip()if not body:continuefor para in body.split("\n\n"): # paragraphs as the secondary boundaryif len(para) <= 500:chunks.append(f"[{section.title}] {para}")else: # re-split oversized paragraphs with overlapstep, overlap = 400, 80for i in range(0, len(para), step - overlap):chunks.append(f"[{section.title}] {para[i:i+step]}")return chunks
3.3 Implementation: Creation and Configuration
The steps in order: create a knowledge base and select an embedding model; upload documents and specify parsing rules and chunking parameters; wait for index construction to finish; then set retrieval parameters, including the recall count, similarity threshold, whether to enable reranking, and the weight distribution for multi-route recall. In the basic settings, the “similarity threshold” filters out low-relevance chunks, while the “recall count” must match the context length; together they determine how much information and how much noise reaches the model.
Pitfalls to avoid: do not switch embedding models after the index is built; do not blindly chase extremely small chunks; keep chunking conventions consistent within one knowledge base; and confirm files are not encrypted or corrupted before uploading.
3.4 Validation: Recall Testing and Iteration
Build a test set of 30–50 questions covering typical phrasings and edge cases, and record for each one whether the correct chunk was recalled and whether the answer was correct. Track recall hit rate and answer accuracy separately: a low hit rate points to problems with chunking or embeddings, while a high hit rate with wrong answers points to problems with the prompt or generation parameters. Use this to locate the bottleneck instead of tuning blindly.
In related practice at Baidu AI Cloud, such a workflow is typically paired with object storage for the original corpus, a log service to record the retrieval chain, and monitoring and alerting to watch response latency and failure rate.
4. Common Questions and Reflections
For structured documents with missing heading levels, automatic structure-based splitting degrades into long chunks, and you should fall back to length-based splitting. Excessive overlap causes duplicated chunks and redundant context. RAG is also not a cure-all: for questions that require synthesizing and reasoning across multiple documents, a single retrieval pass is often insufficient, so multi-round retrieval or query rewriting is needed.
The limitation is that chunking strategy depends heavily on corpus characteristics and has no universally optimal parameters; building an evaluation set is relatively costly; and the added latency from reranking requires a trade-off between experience and accuracy. Future work could explore adaptive chunking combined with query rewriting to keep reducing the manual tuning burden.
