Editorial responsibility: Flatkey Team. References verified on 23 November 2026.
Chunking in RAG means dividing documents into fragments that a system can retrieve and use as context. The aim is not to produce lots of small blocks: it is to preserve the information needed to answer a question, with a reference that lets you return to the original document.
Here we are discussing document preparation for retrieval-augmented generation, not the grouping technique used to memorise information. There is also no chunk size that works best in every system. The document structure, the questions, the embedding model and what you do with the results all affect the decision. Pinecone explains these variables in its guide to chunking strategies.
What a useful chunk should preserve
A retrieved block can contain the word you are looking for and still be insufficient. Imagine a policy with a rule in one sentence and its exception in the next: if the cut separates them, retrieving only the first sentence can lead to an incorrect answer.
Before choosing a length, check three things:
- Meaning: can the statement be understood without a preceding reference that has been left out?
- Evidence: does it include the condition, exception, unit or date that changes the answer?
- Provenance: can you identify the source document, section and revision?
Keep document and chunk identifiers, location and revision. Keep headings with the rows of a table, and instructions with the context the code needs. Check this against the text extracted from the document.
First define the unit: characters, words or tokens
“A block of 300” does not describe a reproducible configuration. You need to state what is being counted and with which function.
Characters are a simple unit for a demonstration. Words require a definition of how you separate punctuation, numbers and abbreviations. Tokens depend on the model’s tokenizer: you cannot automatically substitute words for them or apply a fixed ratio to all Spanish text.
In the official LangChain recursive splitter example, length_function=len counts characters. A parameter being called chunk_size does not make it a token limit.
You also need to distinguish a default from a universal recommendation. The Amazon Bedrock documentation describes a default strategy of approximately 300 tokens that attempts to keep sentences complete. That is the behaviour of that service, not evidence that 300 is the best size for your documents.
How to choose between fixed size, structure and semantics
| Strategy | When it may be useful | What to check |
|---|---|---|
| Fixed length | You need a simple, controllable baseline for comparing changes. | Cuts within sentences, conditions or tables. |
| Structure-based splitting | Titles, paragraphs, lists or sections express useful relationships. | Overly long sections, headings without content and structure lost during extraction. |
| Recursive splitting | You want to try to preserve larger units before resorting to smaller separators. | The actual separators, each block’s effective length and what the length function means. |
| Semantic splitting | You want the cut to depend on relationships in meaning calculated by a specific method. | The model, threshold, implementation and additional cost; splitting at sentence boundaries alone does not make it semantic. |
Do not choose a label because of how it sounds. A paragraph splitter may preserve a policy better than a fixed cut, but it may also leave an enormous section. A semantic splitter introduces other variables that you will need to hold constant during comparison. Bedrock, for example, documents semantic options that use sentence embeddings and may involve additional costs; that description does not automatically apply to every implementation.
What overlap adds and what it costs
Overlap repeats part of the end of one chunk at the beginning of the next. It can preserve a relationship near a cut, but it also adds duplication.
Measure how many blocks you produce and how much text you repeat. If the top results contain almost the same sentence, you can use some of the available context without adding evidence. Do not count several copies of the same answer as several independent hits.
The configured overlap does not guarantee an identical amount of shared text in every splitter either. Inspect the blocks produced and their positions in the document. The LangChain documentation presents it as a target overlap; the result depends on the splitting and its separators.
Local test: five configurations and eight questions
On 20 November 2026, we ran a CPU test with Python 3.14.6, macOS ARM and only the standard library. We used three synthetic Spanish documents—Archivo Brisa, Huerto Nube and Taller Faro—687 words and eight questions, with evidence marked before scoring results. These are imaginary institutions, with no customer data. On 23 November, we repeated the run by copying the complete code from this guide: the same inputs produced the same results.
The unit was a Unicode alphanumeric sequence identified by [^\W_]+: words for this exercise, not model tokens. We normalised with casefold, retained accents and neither removed stop words nor applied stemming. The retriever used the script’s BM25 formula, with k1=1.2, b=0.75 and top-k=3; ties were broken by document and start position. Only positive scores were included. Each index recalculated document frequencies, IDF and average block length: its scores are not comparable across configurations. For a reference on the formula and its parameters, see the Apache Lucene BM25Similarity documentation; our script is our own educational implementation and does not run Lucene.
First, we changed the length of hard cuts without overlap. We then compared 48 words with 12 words of overlap and, separately, a maximum of 48 words while looking for the last available sentence ending. If a sentence exceeds the maximum, that variant falls back to a hard cut. Each document was split separately. The lengths are maxima: the last block of each document may be shorter.
What we measured and what happened
“Document” counts questions with a block from the correct document among the top three. “Evidence in one block” requires a single result to contain all the necessary intervals. The third measure allows all the words in those intervals to be assembled from several correct results, without counting duplicates. Every cell uses the same denominator: eight questions.
| Configuration | Blocks | Document @3 | Evidence in one block @3 | Evidence across blocks @3 |
|---|---|---|---|---|
| 24 words, no overlap | 30 | 8/8 | 2/8 | 4/8 |
| 48 words, no overlap | 15 | 8/8 | 6/8 | 7/8 |
| 96 words, no overlap | 9 | 8/8 | 7/8 | 8/8 |
| 48 words, overlap of 12 | 19 | 8/8 | 5/8 | 5/8 |
| Up to 48 words, sentence boundary | 18 | 8/8 | 7/8 | 7/8 |
The correct document always appeared, but that hid a loss of evidence. Nor can we declare 96 words the winner: it retrieved an average of 237.5 words per query, compared with 137 for 48 words. Holding top-k constant does not equalise the context.
An actual overlap failure
For the question about the two conditions for using Huerto Nube’s shredder, 48 words without overlap kept the training requirement and the presence of the person in charge together. With overlap, the first result ended at “durante su”, leaving out “uso”. The other two results did not complete that evidence. Our strict criterion recorded this as a failure; it does not mean that an incorrect LLM answer was observed, because we did not run an LLM.
Overlap improved another question, about collection by a third party at Taller Faro: it brought the identifier, form and authorisation together in one block. Even so, it lost two hits and gained one on the complete-single-block measure. It emitted 879 words compared with the original 687: 192 repeated words, an additional 27.95% in this corpus. This is not an API bill or a latency measurement.
How to repeat and extend the check
The run uses chunking_experiment.py, inputs.json and its outputs results.json and summary.csv. The SHA-256 hash of the inputs is a78903cb675c64229541f4f7d15b31ee. The script saves the manifest before scoring, each block’s positions and the complete ranking for each query.
84f4ab47242773b29bf09467dd54408f
To extend the test, hold documents, questions, evidence and the retriever constant while changing one variable. Read the failures before choosing parameters. We did not use embeddings, an LLM, a vector database, a reranker or a GPU here: we measured lexical retrieval and literal coverage in a small corpus, not semantic quality or production answers.
What to change after observing a problem
If the correct document appears but a nearby condition is missing, inspect boundaries, paragraph preservation or retrieval of neighbouring context. If too many repeated results appear, review overlap and deduplication. If the right document does not appear at all, also check extraction, filters and the retriever: increasing the block size does not identify the cause on its own.
A small test can reveal specific mechanisms and errors. The corpus and questions were written for this demonstration, without independent annotation. The test does not demonstrate statistical significance or represent every question a business might ask. Before taking a decision into production, use representative queries and retain the difficult cases.
To separate retrieval, citations and generation, continue with how to evaluate a RAG system with an LLM. If you need to build vector search, see the embeddings integration guide: changing how you split text and changing the representation model are different decisions.
When to split and index again
Recheck the process when the document, extractor, splitting configuration or embedding model changes. Preserve the relationship between chunks and revisions so that you can identify which content needs rebuilding.
Your choice of chunking should end with a configuration you can explain. Save questions, conditions and results so you can compare the next change.
You can return to the Flatkey blog in English for other guides. This guide is the editorial responsibility of Flatkey Team; see the information about the Flatkey team and contact details. Links to Flatkey content belong to our own website. We do not present this exercise as an independent evaluation of providers or as a customer case study.
Complete code to repeat the experiment
Save this code as chunking_experiment.py in an empty folder and run python3 chunking_experiment.py. It includes the three synthetic documents, the eight questions, their evidence and all configurations; it needs neither a network connection nor external packages. It generates the JSON and CSV result files in the same folder; rerunning it overwrites those output files. The run has been checked with Python 3.14.6.
#!/usr/bin/env python3
"""Synthetic Spanish lexical retrieval experiment; Python standard library only."""
import collections
import hashlib
import json
import math
import platform
import re
import sys
from datetime import datetime, timezone
from pathlib import Path
ROOT = Path(__file__).resolve().parent
# Inputs and evidence are fixed before configurations are executed.
DOCUMENTS = [
{"id": "brisa", "title": "Archivo Brisa: préstamo y consulta", "text": """El Archivo Brisa es una institución ficticia de este ejemplo. Su sala de consulta abre de martes a viernes. Las visitas del sábado requieren una reserva previa. El acceso a la sala no permite retirar material del edificio.
Para solicitar una caja, la persona visitante entrega una ficha con el código de la colección. El personal comprueba la disponibilidad y lleva la caja a la mesa asignada. Solo se permite consultar una caja a la vez. Antes de pedir otra, hay que devolver la anterior al mostrador.
Las fotografías sin flash están permitidas únicamente cuando la ficha de la colección indica acceso abierto. Si la ficha marca acceso restringido, es necesaria una autorización escrita del responsable del archivo. La reserva de una visita no sustituye esa autorización. Este requisito también se aplica a fotografías hechas con un teléfono.
Para renovar una reserva, se envía el código de confirmación antes del cierre del jueves. El personal responde por el mismo canal. La renovación no queda confirmada hasta recibir la respuesta. Si no llega respuesta, se conserva la fecha original y debe consultarse al mostrador.
Los documentos deben permanecer en sus carpetas. No se utilizan clips ni notas adhesivas sobre el material. Las incidencias se anotan en la ficha de consulta. El personal del Archivo Brisa revisa esa ficha al terminar la visita."""},
{"id": "huerto", "title": "Huerto Nube: herramientas y turnos", "text": """El Huerto Nube es una organización ficticia de este ejemplo. Sus turnos de trabajo se publican en el tablón del cobertizo. El turno de riego comienza después de la reunión de apertura. La participación en la reunión no concede permiso para utilizar todas las herramientas.
Las herramientas manuales se recogen en el cobertizo y se devuelven limpias al terminar el turno. Para usar la trituradora hace falta completar la sesión práctica de seguridad. Además, la persona responsable del turno debe estar presente durante su uso. Una inscripción en el calendario no equivale a completar la sesión práctica.
Cuando el depósito está por debajo de la marca azul, se suspende el riego automático. En ese caso, la persona responsable registra la incidencia y distribuye el agua con regaderas. El riego automático solo vuelve a activarse después de revisar el nivel y cerrar la incidencia. No se activa por el simple cambio de turno.
Para cambiar una reserva del bancal, se escribe el número de parcela en la hoja de cambios. El nuevo turno solo queda confirmado cuando la persona coordinadora firma esa hoja. Si falta la firma, sigue vigente la reserva anterior. La confirmación por conversación informal no sustituye la firma.
Al final de la jornada se guardan las semillas en recipientes cerrados. Cada recipiente conserva la etiqueta de la variedad. Las etiquetas ilegibles se separan para revisión. Estas reglas se refieren únicamente al Huerto Nube imaginario del experimento."""},
{"id": "taller", "title": "Taller Faro: piezas y recogida", "text": """El Taller Faro es un taller ficticio de este ejemplo. La recepción anota cada pieza con un identificador y una descripción. La persona que entrega la pieza recibe una copia de la ficha. Esa copia sirve para consultar el estado del trabajo.
Las piezas pintadas se guardan en el estante verde durante el secado. Las piezas sin pintar se colocan en el estante gris. El color del estante identifica la etapa del proceso, no a la persona propietaria. El personal no cambia una pieza de estante hasta revisar su ficha.
Para recoger una pieza reparada se presenta el identificador y la copia de la ficha. Si recoge otra persona, también debe presentar una autorización firmada por quien entregó la pieza. Un mensaje verbal no sustituye la autorización. La recepción registra el nombre de quien realiza la recogida.
Si una pieza no supera la revisión final, vuelve a la mesa de ajuste. En ese caso se comunica una nueva fecha de revisión, no una fecha de recogida. La recogida se confirma solo después de superar la revisión final. La fecha provisional escrita en la ficha no constituye esa confirmación.
Los materiales sobrantes se separan por tipo al cerrar la jornada. El registro de incidencias conserva el identificador de la pieza, la fecha y el motivo. Estas normas describen el Taller Faro imaginario; no son instrucciones de un servicio real."""},
]
QUESTIONS = [
{"id": "q1", "query": "¿Cuándo requieren reserva las visitas del Archivo Brisa?", "doc_id": "brisa", "evidence": ["Las visitas del sábado requieren una reserva previa."]},
{"id": "q2", "query": "¿Qué autorización hace falta para fotografiar una colección restringida en el Archivo Brisa?", "doc_id": "brisa", "evidence": ["Si la ficha marca acceso restringido, es necesaria una autorización escrita del responsable del archivo."]},
{"id": "q3", "query": "¿Cómo se confirma la renovación de una reserva del Archivo Brisa?", "doc_id": "brisa", "evidence": ["La renovación no queda confirmada hasta recibir la respuesta."]},
{"id": "q4", "query": "¿Qué dos condiciones exige el Huerto Nube para usar la trituradora?", "doc_id": "huerto", "evidence": ["Para usar la trituradora hace falta completar la sesión práctica de seguridad.", "Además, la persona responsable del turno debe estar presente durante su uso."]},
{"id": "q5", "query": "¿Qué ocurre cuando el depósito baja de la marca azul en el Huerto Nube?", "doc_id": "huerto", "evidence": ["Cuando el depósito está por debajo de la marca azul, se suspende el riego automático.", "En ese caso, la persona responsable registra la incidencia y distribuye el agua con regaderas."]},
{"id": "q6", "query": "¿Cuándo queda confirmado un cambio de reserva del bancal del Huerto Nube?", "doc_id": "huerto", "evidence": ["El nuevo turno solo queda confirmado cuando la persona coordinadora firma esa hoja."]},
{"id": "q7", "query": "¿Qué presenta otra persona para recoger una pieza del Taller Faro?", "doc_id": "taller", "evidence": ["Para recoger una pieza reparada se presenta el identificador y la copia de la ficha.", "Si recoge otra persona, también debe presentar una autorización firmada por quien entregó la pieza."]},
{"id": "q8", "query": "¿Una nueva fecha de revisión confirma la recogida en el Taller Faro?", "doc_id": "taller", "evidence": ["En ese caso se comunica una nueva fecha de revisión, no una fecha de recogida.", "La recogida se confirma solo después de superar la revisión final."]},
]
CONFIGS = [
{"id": "size_24", "stage": "size", "size_words": 24, "overlap_words": 0, "boundary": "hard"},
{"id": "size_48", "stage": "size", "size_words": 48, "overlap_words": 0, "boundary": "hard"},
{"id": "size_96", "stage": "size", "size_words": 96, "overlap_words": 0, "boundary": "hard"},
{"id": "overlap_12", "stage": "overlap", "size_words": 48, "overlap_words": 12, "boundary": "hard"},
{"id": "sentence_48", "stage": "boundary", "size_words": 48, "overlap_words": 0, "boundary": "sentence"},
]
WORD = re.compile(r"[^\W_]+", re.UNICODE)
TOP_K, K1, B = 3, 1.2, 0.75
def words(text):
return list(WORD.finditer(text))
def digest(data):
return hashlib.sha256(data).hexdigest()
def encode(data):
return (json.dumps(data, ensure_ascii=False, indent=2) + "\n").encode()
def make_chunks(doc, config):
matches = words(doc["text"])
n, start = len(matches), 0
# The endpoint of each sentence expressed as an exclusive word index.
sentence_ends = set()
for i, match in enumerate(matches):
next_start = matches[i + 1].start() if i + 1 < n else len(doc["text"])
if re.search(r"[.!?]", doc["text"][match.end():next_start]):
sentence_ends.add(i + 1)
sentence_ends.add(n)
chunks = []
while start < n:
end = min(start + config["size_words"], n)
if config["boundary"] == "sentence":
possible = [e for e in sentence_ends if start < e <= end]
if possible:
end = max(possible)
# A sentence over the cap falls back to a hard cut. None assumed absent.
char_start, char_end = matches[start].start(), matches[end - 1].end()
chunks.append({"id": f"{doc['id']}:{start:04d}:{end:04d}", "doc_id": doc["id"],
"start_word": start, "end_word": end, "start": char_start, "end": char_end,
"text": doc["text"][char_start:char_end], "word_count": end - start})
if end == n:
break
start = end - config["overlap_words"]
return chunks
def main():
ROOT.mkdir(parents=True, exist_ok=True)
for q in QUESTIONS:
doc = next(d for d in DOCUMENTS if d["id"] == q["doc_id"])
spans = []
for evidence in q["evidence"]:
assert doc["text"].count(evidence) == 1, (q["id"], "evidence_not_unique")
start = doc["text"].index(evidence)
# Character ranges include punctuation; chunks cover lexical words only.
# Trim trailing punctuation for the containment metric, retaining source quote.
last = words(evidence)[-1].end()
spans.append({"start": start, "end": start + last, "text": evidence})
q["evidence_spans"] = spans
inputs = {"synthetic": True, "documents": DOCUMENTS, "questions": QUESTIONS,
"configs": CONFIGS, "top_k": TOP_K, "bm25": {"k1": K1, "b": B},
"normalisation": "Unicode alphanumeric words via [^\\W_]+; casefold; accents retained; no stopword removal or stemming",
"tie_break": "descending score, ascending doc_id, ascending start_word; positive scores only"}
inputs_bytes = encode(inputs)
(ROOT / "inputs.json").write_bytes(inputs_bytes)
# The same manifest is written before any scoring, so evidence cannot be selected from results.
(ROOT / "predeclared-inputs.sha256").write_text(digest(inputs_bytes) + " inputs.json\n")
all_runs, summary = [], []
total_original_words = sum(len(words(d["text"])) for d in DOCUMENTS)
for config in CONFIGS:
chunks = [c for doc in DOCUMENTS for c in make_chunks(doc, config)]
counts = [collections.Counter(m.group().casefold() for m in words(c["text"])) for c in chunks]
lengths = [sum(c.values()) for c in counts]
avgdl = sum(lengths) / len(lengths)
df = collections.Counter(term for counter in counts for term in counter)
results = []
for q in QUESTIONS:
terms = set(m.group().casefold() for m in words(q["query"]))
scored = []
for chunk, counter, dl in zip(chunks, counts, lengths):
score = 0.0
for term in sorted(terms):
tf = counter.get(term, 0)
if tf:
idf = math.log(1 + (len(chunks) - df[term] + 0.5) / (df[term] + 0.5))
score += idf * tf * (K1 + 1) / (tf + K1 * (1 - B + B * dl / avgdl))
scored.append({"chunk_id": chunk["id"], "doc_id": chunk["doc_id"], "start": chunk["start"], "end": chunk["end"], "start_word": chunk["start_word"], "word_count": chunk["word_count"], "score": score})
ranked = sorted(scored, key=lambda s: (-s["score"], s["doc_id"], s["start_word"]))
top = [s for s in ranked if s["score"] > 0][:TOP_K]
correct = [s for s in top if s["doc_id"] == q["doc_id"]]
def contains(chunk, span):
return chunk["start"] <= span["start"] and chunk["end"] >= span["end"]
single = any(all(contains(c, span) for span in q["evidence_spans"]) for c in correct)
gold_doc = next(d for d in DOCUMENTS if d["id"] == q["doc_id"])
evidence_words = [
{"start": m.start(), "end": m.end()}
for m in words(gold_doc["text"])
if any(span["start"] <= m.start() and m.end() <= span["end"] for span in q["evidence_spans"])
]
union = all(any(contains(c, word) for c in correct) for word in evidence_words)
results.append({"question_id": q["id"], "query": q["query"], "gold_doc_id": q["doc_id"],
"gold_evidence": q["evidence_spans"], "document_hit_at_3": bool(correct),
"single_chunk_complete_evidence_at_3": single,
"multi_chunk_complete_evidence_at_3": union,
"retrieved_words_at_3": sum(c["word_count"] for c in top),
"top_3": top, "all_scores_ranked": ranked})
emitted_words = sum(lengths)
row = {"config": config["id"], "chunks": len(chunks), "original_words": total_original_words,
"emitted_words": emitted_words, "repeated_words": emitted_words - total_original_words,
"redundancy_fraction": (emitted_words - total_original_words) / total_original_words,
"min_chunk_words": min(lengths), "max_chunk_words": max(lengths),
"mean_chunk_words": avgdl, "question_count": len(QUESTIONS),
"mean_retrieved_words_at_3": sum(r["retrieved_words_at_3"] for r in results) / len(results),
"document_hits_at_3": sum(r["document_hit_at_3"] for r in results),
"single_chunk_complete_evidence_hits_at_3": sum(r["single_chunk_complete_evidence_at_3"] for r in results),
"multi_chunk_complete_evidence_hits_at_3": sum(r["multi_chunk_complete_evidence_at_3"] for r in results)}
all_runs.append({"config": config, "summary": row, "chunks": chunks, "results": results})
summary.append(row)
output = {"started_and_completed_at": datetime.now(timezone.utc).isoformat(),
"environment": {"python": sys.version, "platform": platform.platform(), "processor": platform.processor(), "dependencies": "Python standard library only", "external_calls": 0},
"input_sha256": digest(inputs_bytes), "script_sha256": digest(Path(__file__).read_bytes()),
"summary": summary, "runs": all_runs}
(ROOT / "results.json").write_bytes(encode(output))
columns = ["config", "chunks", "emitted_words", "repeated_words", "redundancy_fraction", "document_hits_at_3", "single_chunk_complete_evidence_hits_at_3", "multi_chunk_complete_evidence_hits_at_3"]
(ROOT / "summary.csv").write_text(",".join(columns) + "\n" + "\n".join(",".join(str(row[c]) for c in columns) for row in summary) + "\n")
failures = [{"config": run["config"]["id"], **result} for run in all_runs for result in run["results"] if not result["single_chunk_complete_evidence_at_3"]]
(ROOT / "all-counterexamples.json").write_bytes(encode(failures))
print(json.dumps({"environment": output["environment"], "input_sha256": output["input_sha256"], "script_sha256": output["script_sha256"], "summary": summary, "counterexamples": len(failures)}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()



