Почему наивное разбиение вредит поиску
Проанализируйте реальные сбои поиска, вызванные неудачным разбиением текста, включая ответы, разделённые границами фрагментов, и потерю контекста из заголовков и названий разделов.
«Почему наивное разбиение вредит поиску» — бесплатный урок AI Engineering Academy на CoddyKit. Это урок 1 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения 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.
Часто задаваемые вопросы
Урок «Почему наивное разбиение вредит поиску» бесплатный?
Да — полный текст урока «Почему наивное разбиение вредит поиску» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс AI Engineering Academy, подпишись на CoddyKit PRO. Курс AI Engineering Academy содержит 4 уроков всего.
Чему я научусь в уроке «Почему наивное разбиение вредит поиску»?
Проанализируйте реальные сбои поиска, вызванные неудачным разбиением текста, включая ответы, разделённые границами фрагментов, и потерю контекста из заголовков и названий разделов. Ты практикуешь AI Engineering Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать AI Engineering Academy?
Предыдущий опыт не требуется. AI Engineering Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 1 из 4.
Сколько времени занимает урок «Почему наивное разбиение вредит поиску»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке AI Engineering Academy?
Да. Каждый урок AI Engineering Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Почему наивное разбиение вредит поиску
- Семантическое разбиение по сходству эмбеддингов
- Поиск по принципу «родительский фрагмент — дочерний» и от малого к большому
- Стратегии для кода и HTML с учётом типа документа