RAG Chunking and Retrieval: A Complete Guide to Building a Knowledge Base

    This article walks through the full pipeline of building a RAG knowledge base, focusing on why chunking is the critical first step and how it trades off semantic completeness, retrieval precision, and context sufficiency. It covers common chunking strategies (fixed-length with overlap, structure-aware, parent-child, and semantic chunking), embedding model selection, reranking as a second stage, the end-to-end construction workflow, and common pitfalls with tuning advice. Readers will learn how to choose chunk granularity, align chunk size with embedding input limits, combine vector and keyword retrieval, and evaluate retrieval quality.

    1. Why Chunking Is the First Dividing Line in Knowledge Base Construction

    In a Retrieval-Augmented Generation (RAG) system, chunking determines what the system can “see” at all. No matter how strong the embedding model is or how accurate the reranker becomes, if the chunk granularity is poorly chosen, meaning gets cut off and context gets fragmented. Retrieval is then forced to match against incomplete information, and the generated output naturally ends up off-topic or factually wrong.

    Chunking is essentially a trade-off among three conflicting goals:

    • Semantic completeness: A chunk should express one complete concept and avoid splitting a definition, a set of steps, or a conclusion apart.
    • Retrieval precision: When chunks are too large, the vector representation is diluted by irrelevant content and similarity becomes less discriminative.
    • Context sufficiency: When chunks are too small, the matched fragment lacks surrounding context, making it hard for the generation model to reason.

    A common engineering rule of thumb is that a chunk’s length should cover “the smallest unit of knowledge that can be answered independently.” For example, a product parameter table, a single operating instruction, or an individual legal clause usually suits shorter chunks, while technical solutions and process descriptions need longer continuous text.

    2. Common Chunking Strategies and Their Use Cases

    2.1 Fixed-Length Splitting with Overlap

    The most basic approach splits text by character or token count and adds a certain overlap. Overlap prevents a key sentence from falling exactly on a split boundary and losing its meaning.

    1. Chunk length: 512 tokens
    2. Overlap window: 64 tokens
    3. Slide step: 448 tokens

    This strategy is simple to implement and cost-controlled, and works well for loosely structured long text, but it is unfriendly to tables, code, and hierarchical headings.

    2.2 Structure-Aware Splitting

    A more mature approach parses the document structure first (heading levels, paragraphs, lists, tables), then splits along semantic boundaries while keeping the “section path” as metadata. For example, if a piece of content belongs to “Deployment Guide > Network Configuration > Port Settings,” that path itself can significantly improve context awareness during retrieval.

    2.3 Parent-Child Chunking and Multi-Granularity Indexing

    One approach that balances precision and context is to use smaller chunks for vector retrieval, then trace back to their parent chunk before feeding it to the generation model. Small chunks ensure accurate matching, while the parent chunk ensures complete information.

    1. # Example: parent-child chunk retrieval logic
    2. child_hits = vector_search(query, top_k=5) # small-granularity hits
    3. parent_ids = [c.parent_id for c in child_hits] # trace back to parents
    4. context = load_parents(parent_ids) # assemble context

    2.4 Semantic Chunking

    By measuring the vector similarity between adjacent sentences, you can detect whether “the topic has shifted” and split where similarity drops sharply. Semantic chunking usually performs better but requires extra computation, making it suitable for corpora with high knowledge density and irregular structure.

    3. Embedding Models: Turning Text into Comparable Vectors

    The embedding model maps chunks into a dense vector space so that semantically similar text sits closer together. Four dimensions matter when choosing one:

    1. Semantic matching ability: Whether it can distinguish paraphrases from content that only overlaps on the surface but is semantically unrelated.
    2. Vector dimension and storage cost: Higher dimensions mean stronger expressiveness, but storage and retrieval overhead in the vector store rise accordingly.
    3. Maximum input length: This must exceed the vast majority of chunk lengths; otherwise silent truncation occurs and information is lost.
    4. Chinese and domain adaptability: General-purpose models often fall short on technical terms, abbreviations, and internal codenames, so fine-tuning on domain corpora may be necessary.

    An often-overlooked practical point: the chunk length must align with the embedding model’s maximum input length. If a chunk is 800 tokens but the model limit is 512, the excess is discarded and the vector only represents the first half of the semantics. This is a frequent root cause of abnormal recall in production.

    4. Reranking Models: Turning “Relevant” into “Most Relevant”

    Vector retrieval is coarse filtering that pursues high recall; a rerank model scores each “query–candidate chunk” pair precisely, pursuing high precision. A typical two-stage flow looks like this:

    1. Stage 1: vector retrieval top 100 (fast, high recall)
    2. Stage 2: rerank to top 5~8 (accurate, fed into generation)

    Reranking delivers the most value when the candidate set is large and many items are semantically close. For example, when a user asks “how to configure a read-only account,” vector retrieval may return many chunks related to “account” and “permission,” while reranking can push the one that truly describes read-only configuration to the top. In engineering, note the added latency from reranking; you can control it by shrinking the candidate set, batch scoring, and caching results.

    5. The Full Knowledge Base Construction Pipeline

    1. Data ingestion and parsing: Support multiple sources such as documents, tables, web pages, and tickets. The parsing stage sets the upper bound for everything downstream, and tables and scanned files need dedicated handling.
    2. Cleaning and normalization: Remove headers, footers, duplicate content, and garbled text; unify terminology and full/half-width characters; strip invalid links and placeholders.
    3. Chunking and metadata tagging: Apply the chosen strategy and write metadata such as source, section path, update time, and permission tags.
    4. Vectorization and indexing: Call the embedding model to generate vectors in batches and write them into the vector store, while keeping the original text and metadata for traceability.
    5. Retrieval and reranking: Hybrid retrieval (keyword + vector) is usually more robust than a single path, and reranking then outputs high-confidence fragments.
    6. Generation and citation: Assemble fragments into context and require the model to answer based on the given material and provide sources, reducing hallucination.
    7. Evaluation and iteration: Build a Q&A evaluation set and track recall hit rate, fragment accuracy, answer correctness, and response latency, then work backward from failure samples to determine whether it is a chunking problem or a model problem.

    6. Common Pitfalls and Tuning Advice

    • Chasing small chunks blindly: Overly fragmented chunks strip away context, showing up as “every sentence is relevant but no conclusion can be assembled.”
    • Ignoring metadata: Without section paths and source information, you cannot perform permission filtering or traceability later.
    • Using vector retrieval only: For queries involving proper nouns, IDs, and model numbers, keyword retrieval is often more reliable, so a hybrid approach is recommended.
    • Skipping incremental updates: A knowledge base evolves continuously and needs document-level incremental rebuilding to avoid the cost and downtime of full rebuilds.

    In practice, you can rely on general cloud capabilities such as object storage for original documents, a message queue for ingestion tasks, a container platform for parsing and vectorization jobs, and logging, monitoring, and alerting services to observe fluctuations in retrieval quality. Baidu AI Cloud offers a fairly complete combination of these general capabilities, making it easier for teams to focus on chunking strategy and the evaluation system itself. Ultimately, the ceiling of knowledge base quality is determined by chunking and evaluation; the model merely realizes that ceiling.