Skip to content

2.3 Deep Dive into Text Splitting

Why Document Splitting Is Critical

Chunking is one of the most underrated parts of RAG systems. At first glance the task seems trivial: you just need to cut a long text into fragments of a suitable size. In practice, however, the choice of splitting strategy directly affects how well the system will work.

The problems become especially visible during testing. If the chunks are too large, the system loses precision. To a question about a specific parameter it may return a 2000-character fragment in which the useful information takes up just one sentence while everything else is superfluous context. The model may try to pick out the essentials, but this is not guaranteed. If the chunks are too small, on the other hand, the system loses coherence: the answer comes out fragmented and, without the surrounding text, becomes hard to understand.

Why split documents at all? There are several reasons. First, the model's context window is limited, and a whole document often simply does not fit into it. Second, embedding-based search works precisely at the level of chunks. If you index a whole document as a single unit, it becomes hard to find specific facts inside it. Third, when generating an answer, the model relies on the context it is given, and the more irrelevant text that context contains, the lower the quality of the final answer.

That is why finding a balance matters here. A chunk should not be a random piece of text. A fragment like "he solved this problem" is useless if it is unclear who is meant and which problem is being discussed. A good chunk contains enough information to be understood on its own and is able to answer a potential question without relying on the neighboring parts of the text.

Size and Overlap: Trade-offs

The chunk size is usually measured in characters or tokens. A typical range is 200 to 2000 characters. As a starting point, about 1000 characters is reasonable, and then you adjust the size based on test results.

Large chunks preserve context better but reduce search precision. In a 2000-character fragment the truly useful information may take up only 100 characters, while the rest becomes noise. Up to a point the model can cope with this, but excess context degrades answer quality and increases token usage.

Small chunks, in contrast, improve search precision but preserve semantic links less well. For example, the answer to the question "what are the system requirements" may be spread across several neighboring paragraphs. If each paragraph is indexed separately, the system has to somehow assemble them together.

This is where the overlap technique helps. Neighboring chunks partially intersect. If the chunk size is 1000 characters and the overlap is 200, then the last 200 characters of the first chunk match the first 200 characters of the second. This reduces the risk of losing information at the boundaries: if an important thought falls on the seam between two fragments, it will still appear in full in at least one of them.

def split_with_overlap(text, chunk_size, overlap):
    chunks = []
    start = 0

    while start < len(text):
        end = start + chunk_size
        chunk = text[start:end]
        chunks.append(chunk)
        start = end - overlap

        if start + overlap >= len(text):
            break

    return chunks

The overlap is usually 10–20% of the chunk size. If you make it too large, the index gets redundant duplication, which can distort search results.

Adaptive Chunking for Different Content Types

A single universal chunk size is rarely enough for all documents. Different types of content require different approaches. An FAQ, for example, already consists of self-contained question-and-answer pairs. Guides usually have a hierarchy of headings. Technical specifications often contain tables and lists that should not be broken apart.

So the strategy can be adaptive: first the document is classified automatically, and then a suitable splitting method is chosen for it. For an FAQ it makes sense to keep each question with its answer as a separate chunk. For guides, split the text by headings and keep the structure in the metadata. For specifications, increase the chunk size so as not to break tables and related blocks of text.

def adaptive_chunking(document, doc_type):
    if doc_type == "faq":
        return split_by_qa_pairs(document)
    elif doc_type == "guide":
        return split_by_headers(document)
    elif doc_type == "specification":
        return split_fixed_size(document, chunk_size=1500, overlap=300)
    else:
        return split_fixed_size(document, chunk_size=1000, overlap=200)

def split_by_qa_pairs(document):
    pattern = r'(Q:|Question:)(.*?)(A:|Answer:)(.*?)(?=Q:|Question:|$)'
    matches = re.findall(pattern, document.page_content, re.DOTALL)

    chunks = []
    for match in matches:
        question = match[1].strip()
        answer = match[3].strip()
        chunk_text = f"Question: {question}\nAnswer: {answer}"

        chunks.append(Document(
            page_content=chunk_text,
            metadata={**document.metadata, "type": "qa"}
        ))

    return chunks

Built-in LangChain Splitters

LangChain provides several ready-made classes for splitting text, and each of them has its own specifics.

CharacterTextSplitter is the simplest option. It splits the text on a given separator, usually a double line break, and merges neighboring pieces until the size limit is reached.

from langchain.text_splitter import CharacterTextSplitter

splitter = CharacterTextSplitter(
    separator="\n\n",
    chunk_size=1000,
    chunk_overlap=200,
    length_function=len
)

chunks = splitter.split_documents(documents)

The problem is that this approach depends on the structure of the text. If there are no separators, or they are rare, the splitter may cut the text arbitrarily in the middle of a sentence.

RecursiveCharacterTextSplitter solves this problem. It uses a hierarchy of separators: first it tries to split by paragraphs, if that does not work, by sentences, and then by words:

from langchain.text_splitter import RecursiveCharacterTextSplitter

splitter = RecursiveCharacterTextSplitter(
    chunk_size=1000,
    chunk_overlap=200,
    separators=["\n\n", "\n", ". ", " ", ""]
)

chunks = splitter.split_documents(documents)

This splitter handles heterogeneous texts more robustly and is often a good default choice for general tasks. It is not tied to a single separator and adapts automatically to the structure of the text.

TokenTextSplitter works with tokens instead of characters:

from langchain.text_splitter import TokenTextSplitter

splitter = TokenTextSplitter(
    chunk_size=500,
    chunk_overlap=50
)

chunks = splitter.split_documents(documents)

This matters when you need to control the consumption of the model's context window. Tokens reflect the real size of the context more accurately. However, different models use different tokenizers, so make sure you use the right one.

Splitting by Document Structure

For documents with explicit structure, there are specialized splitters. MarkdownHeaderTextSplitter splits Markdown by headings and keeps the hierarchy in the metadata:

from langchain.text_splitter import MarkdownHeaderTextSplitter

headers_to_split_on = [
    ("#", "Header 1"),
    ("##", "Header 2"),
    ("###", "Header 3"),
]

splitter = MarkdownHeaderTextSplitter(headers_to_split_on=headers_to_split_on)
chunks = splitter.split_text(markdown_text)

for chunk in chunks:
    print(f"Headers: {chunk.metadata}")
    print(f"Content: {chunk.page_content[:100]}...")

Each chunk receives information about its parent headings. During search this makes it possible to understand the context.

A similar approach exists for code:

from langchain.text_splitter import (
    Language,
    RecursiveCharacterTextSplitter
)

python_splitter = RecursiveCharacterTextSplitter.from_language(
    language=Language.PYTHON,
    chunk_size=1000,
    chunk_overlap=100
)

chunks = python_splitter.split_text(python_code)

The code splitter respects syntactic boundaries: it splits between functions and classes, not in the middle of an expression or a block.

Characters Versus Tokens

The choice between characters and tokens as the unit of measurement depends on what matters more to you. Characters are simpler to understand and debug: 1000 characters always look predictable. Tokens, in turn, reflect the real consumption of the model's context window more accurately, but their number depends on the language and on the specific text.

For Russian, this difference is especially noticeable. Cyrillic is tokenized differently from Latin script, so a fragment of Russian text of the same character length can take up more tokens. If your project works mainly with Russian-language documents, it is reasonable to measure the size in tokens and leave an additional margin.

import tiktoken

def count_tokens(text, model="gpt-5"):
    encoding = tiktoken.encoding_for_model(model)
    return len(encoding.encode(text))

def estimate_chunk_tokens(text, chunk_size_chars):
    sample = text[:min(5000, len(text))]
    tokens_per_char = count_tokens(sample) / len(sample)
    return int(chunk_size_chars * tokens_per_char)

Cleaning and Enriching Chunks

After splitting, chunks often need additional processing. Empty fragments, pieces made of whitespace only, or chunks that are too short only degrade the quality of the index and waste resources:

def postprocess_chunks(chunks, min_length=50):
    processed = []

    for chunk in chunks:
        text = chunk.page_content.strip()

        if len(text) < min_length:
            continue

        if not any(c.isalpha() for c in text):
            continue

        processed.append(Document(
            page_content=text,
            metadata=chunk.metadata
        ))

    return processed

Sometimes it is useful to include part of the context from the metadata in the chunk itself: the section name, the path in the hierarchy, the source. This improves the quality of the embeddings, because the model sees not an isolated fragment but text embedded in a clear structure:

def add_context_to_chunk(chunk):
    context_parts = []

    if chunk.metadata.get("Header 1"):
        context_parts.append(f"Section: {chunk.metadata['Header 1']}")

    if chunk.metadata.get("Header 2"):
        context_parts.append(f"Subsection: {chunk.metadata['Header 2']}")

    if chunk.metadata.get("source"):
        context_parts.append(f"Source: {chunk.metadata['source']}")

    context = "\n".join(context_parts)

    enhanced_content = f"{context}\n\n{chunk.page_content}" if context else chunk.page_content

    return Document(
        page_content=enhanced_content,
        metadata=chunk.metadata
    )

Questions for Reflection and Practice

Theoretical questions

  1. Explain why splitting documents into chunks is necessary for RAG systems and which problems it solves.

  2. How does the chunk size affect search precision and context completeness, and what trade-offs do you have to make when choosing it?

  3. Why is overlap between chunks needed, and what ratio of chunk size to overlap is usually used?

  4. What is the difference between CharacterTextSplitter and RecursiveCharacterTextSplitter, and when is each one preferable?

  5. How does RecursiveCharacterTextSplitter work, and why is it more robust on heterogeneous texts?

  6. Which specialized splitters exist for code and Markdown, and what advantages do they provide?

  7. When is measuring in characters preferable to tokens, and vice versa, especially for Russian-language content?

  8. How does splitting by Markdown headings help preserve the document's structure and improve search quality?

  9. Which post-processing steps for chunks help improve index quality?

  10. How do you adapt the splitting strategy for documents of different types (FAQs, guides, specifications)?

Practical exercises

  1. Implement a function that splits text by characters with a given chunk size and overlap.

  2. Create a class that uses RecursiveCharacterTextSplitter with a correct hierarchy of separators for Russian-language text.

  3. Implement a chunk post-processing function that removes empty, too-short, and non-text fragments.

  4. Create a function that enriches chunks with context information from the metadata.

  5. Implement a function that counts tokens and estimates chunk sizes in tokens for a specific model.

  6. Create a class for adaptive splitting of documents of different types with automatic classification.