0Pricing
AI Engineering Academy · 课时

朴素分块为何会损害检索效果

分析由不佳分块导致的真实检索失败案例,包括答案被分割到不同分块之间,以及标题和章节名称所提供的上下文丢失。

朴素分块为何会损害检索效果 是 CoddyKit 上的免费 AI Engineering Academy 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 AI Engineering Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 AI Engineering Academy 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

The Cost of Poor Chunking

Chunking is the process of splitting documents into smaller pieces before embedding them into a vector store. The way you chunk determines what context is available during retrieval. Poor chunking is one of the most common and impactful causes of RAG system failures.

Answers Split Across Boundaries

Imagine a document that says: 'The refund policy is 30 days from purchase. Customers must include the original receipt.' If a fixed-size splitter cuts after 'purchase.', these two sentences land in different chunks. A query about the refund policy may only retrieve the first half — making the model unable to mention the receipt requirement.

Lost Context from Headers

Documents often use section headers to provide meaning. Consider a table titled 'Pricing for Enterprise Plans' followed by rows of numbers. If the header and the table land in different chunks, the retrieved table chunk contains numbers with no label — the model cannot answer 'What is the Enterprise price?' correctly.

Fixed-Size Chunking Pitfalls

Fixed-size chunking splits text every N characters or tokens regardless of sentence boundaries. This is fast and simple but breaks mid-sentence frequently. A chunk ending with 'The model was trained on' and a following chunk starting with 'a dataset of 500 billion tokens' are each meaningless without the other.

from langchain.text_splitter import CharacterTextSplitter

# Naive fixed-size: may break mid-sentence
splitter = CharacterTextSplitter(chunk_size=200, chunk_overlap=0)
chunks = splitter.split_text(document_text)
print(f'Created {len(chunks)} chunks')
print('First chunk:', chunks[0])

Overlap Does Not Always Help

A common fix is adding chunk overlap — repeating the last N tokens of a chunk at the start of the next. This helps with split sentences but introduces redundancy and can confuse retrievers when two highly similar chunks both get retrieved. Overlap is a band-aid, not a cure for structural chunking problems.

# Overlap helps partially but adds redundancy
splitter = CharacterTextSplitter(
    chunk_size=500,
    chunk_overlap=50  # last 50 chars repeated in next chunk
)
chunks = splitter.split_text(document_text)

Measuring Retrieval Failure Rate

You can measure how often your chunking hurts retrieval by building a small golden evaluation set: a list of questions with known correct source passages. Then check how often the correct passage is in the top-k retrieved chunks. A low hit rate often reveals chunking problems before you even look at generation quality.

def hit_rate(queries_and_answers, retriever, k=5):
    hits = 0
    for query, expected_text in queries_and_answers:
        results = retriever.retrieve(query, k=k)
        retrieved_texts = [r.page_content for r in results]
        if any(expected_text in text for text in retrieved_texts):
            hits += 1
    return hits / len(queries_and_answers)

Code and Structured Data Problems

Code files, JSON, and tables have logical units — functions, objects, table rows — that should not be split. Splitting a Python function definition across two chunks means neither chunk is independently understandable. A retriever that finds the second chunk sees argument-less code with no context.

# Bad: splits code arbitrarily
bad_chunk_1 = 'def calculate_price(item, qty'  # incomplete!
bad_chunk_2 = ', discount):\n    return item.price * qty * (1 - discount)'

# Good: keep the full function together
good_chunk = 'def calculate_price(item, qty, discount):\n    return item.price * qty * (1 - discount)'

Long Documents and Middle Content Loss

Research on LLMs shows the 'lost in the middle' phenomenon: when many chunks are retrieved and stuffed into a prompt, the model pays attention to content near the beginning and end but tends to ignore the middle. Poor chunking that produces many small low-quality chunks makes this worse by diluting the relevant signal.

Diagnosing Bad Chunks Manually

A quick diagnostic is to print a random sample of your chunks and read them. Ask yourself: Is this chunk meaningful in isolation? If a user asked a question, could the model answer it from this chunk alone? Chunks that reference undefined pronouns ('He said that...'), incomplete code, or context-free numbers are red flags.

import random

def audit_chunks(chunks, sample_size=10):
    sample = random.sample(chunks, min(sample_size, len(chunks)))
    for i, chunk in enumerate(sample):
        print(f'--- Chunk {i+1} ({len(chunk)} chars) ---')
        print(chunk[:300])
        print()

When Chunk Size Is Too Large

Very large chunks hurt retrieval precision. A 2000-token chunk about a broad topic may match many queries but deliver too much noise to the LLM. The model has to find the needle in the haystack within that chunk. Smaller, focused chunks improve precision at the cost of potentially missing surrounding context.

Strategies That Fix These Problems

Better alternatives to naive fixed-size chunking include: sentence-boundary splitting that never cuts mid-sentence, semantic chunking that splits at topic boundaries, parent-child chunking that preserves broader context, and document-aware splitting that respects code functions, HTML tags, and Markdown headers. Each lesson ahead covers one of these.

Quick Check

Test your understanding of chunking failure modes from this lesson.

Lesson Recap

In this lesson you learned: naive fixed-size chunking breaks sentence and section boundaries, overlap is a partial fix but adds redundancy, and chunk quality directly determines retrieval hit rate. Next up we explore semantic chunking, which splits text at natural topic boundaries using embedding similarity.

常见问题解答

「朴素分块为何会损害检索效果」课时是免费的吗?

是的 — 「朴素分块为何会损害检索效果」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 AI Engineering Academy 课程的其余内容,请升级到 CoddyKit PRO。 AI Engineering Academy 课程共包含 4 节课。

「朴素分块为何会损害检索效果」这节课中我会学到什么?

分析由不佳分块导致的真实检索失败案例,包括答案被分割到不同分块之间,以及标题和章节名称所提供的上下文丢失。 你通过在浏览器中直接运行的动手代码来练习 AI Engineering Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 AI Engineering Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 AI Engineering Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。

「朴素分块为何会损害检索效果」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 AI Engineering Academy 课中编写并运行代码吗?

能。每节 AI Engineering Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 朴素分块为何会损害检索效果
  2. 使用嵌入相似度进行语义分块
  3. 父子分块与由小到大的检索
  4. 针对代码和 HTML 的文档专用策略
← 返回 AI Engineering Academy