Loading and Chunking Documents
🎯 Introduction
In the previous lesson, we built a RAG question-answering program using three short passages. Real source material might be a long product manual: retrieving the entire document makes it difficult to return only the parts relevant to a question.
Before generating embeddings, we therefore usually divide documents into smaller chunks. In this lesson, we will read a simple Markdown file, split it into paragraphs, and preserve its section headings and source information.
🧱 Why Split Documents into Chunks?
Suppose a membership guide covers refunds, shipping, and after-sales support. When a user asks about the refund window, the program needs the refund policy, rather than the entire guide.
Length is not the only consideration. For example, a policy might say, “You can request a refund within 7 days of purchase. Sale items are nonrefundable.” Splitting between these sentences could leave a retrieval result with only the first sentence, omitting an important restriction.
Common chunking approaches include:
| Approach | Characteristics | Common uses |
|---|---|---|
| Fixed length | Makes chunk size easy to control, but can split a complete thought | Plain text with little structure |
| Headings and paragraphs | Preserves the original structure and meaning where possible | Markdown and technical documentation |
| Overlapping chunks | Repeats some content between adjacent chunks to reduce information loss at boundaries | Splitting longer passages further |
We will start with the simplest approach: split by paragraph and keep the associated heading. We do not need to implement the other approaches yet.
🛠 Read a Markdown Document
Create guide.md with the following content:
# Membership Guide
## Refunds
You can request a refund within 7 days of purchase. Sale items are nonrefundable.
## Shipping
Standard orders ship within 48 hours of payment.
Use the built-in file API in Node.js 24.x; no additional dependencies are needed. Create 03.chunk.mjs in the same directory:
import { readFile } from "node:fs/promises";
const raw = await readFile("guide.md", "utf8");
const paragraphs = raw
.split(/\n\s*\n/)
.map((part) => part.trim())
.filter(Boolean);
console.log(JSON.stringify(paragraphs, null, 4));
Here, split(/\n\s*\n/) splits on blank lines, trim() removes whitespace from either end of each paragraph, and filter(Boolean) removes empty entries. Run:
node 03.chunk.mjs
The output is:
[
"# Membership Guide",
"## Refunds",
"You can request a refund within 7 days of purchase. Sale items are nonrefundable.",
"## Shipping",
"Standard orders ship within 48 hours of payment."
]
Notice that headings are separate paragraphs too. If we retrieve these paragraphs as they are, the refund policy will not include its “Refunds” section heading. Let’s address that next.
🧩 Preserve a Heading and Source for Each Chunk
In the same 03.chunk.mjs file, keep the code that reads the file and creates paragraphs, then replace the final console.log(...) with:
const chunks = [];
let heading = "";
for (const paragraph of paragraphs) {
if (/^#{1,6}\s+/.test(paragraph)) {
heading = paragraph.replace(/^#{1,6}\s+/, "");
continue;
}
chunks.push({
text: `${heading}\n${paragraph}`,
source: "guide.md",
heading
});
}
console.log(JSON.stringify(chunks, null, 4));
This code does two main things:
- When it encounters a Markdown heading, it records the current heading without creating a separate chunk for it.
- When it encounters a body paragraph, it creates a chunk, includes the most recent heading in
text, and also savesheadingand the filename assource.
Run node 03.chunk.mjs again. The output is:
[
{
"text": "Refunds\nYou can request a refund within 7 days of purchase. Sale items are nonrefundable.",
"source": "guide.md",
"heading": "Refunds"
},
{
"text": "Shipping\nStandard orders ship within 48 hours of payment.",
"source": "guide.md",
"heading": "Shipping"
}
]
Each body paragraph is now a chunk with a heading. You can pass text to an embedding model to generate a vector, then use source and heading to show users where a retrieved chunk came from.
Including the heading in text preserves some context for retrieval. The separate heading and source fields store source metadata for display later.
❓ Knowledge Check
Q: Why should a chunk include source information as well as its text?
Retrieval needs to identify both relevant text and the file and section it came from. This lets the application provide verifiable sources when generating an answer, rather than returning an answer with no attribution.
🧪 Exercise
Add a ## After-Sales Support section to the end of guide.md, with two body paragraphs separated by a blank line. Run 03.chunk.mjs and inspect the resulting chunks.
Success criteria: The output contains two additional chunks, both with heading set to After-Sales Support and source set to guide.md. The ## After-Sales Support heading does not become a separate chunk.
🎉 Congratulations! You can now read and split simple Markdown documents while preserving each chunk’s heading and source.
Your First RAG Application
Use embeddings and in-memory vector search to retrieve relevant content from three passages, then call a model to generate an answer.
Vector Databases
Understand how vector databases differ from MySQL and Redis, store chunk vectors in Qdrant, and verify retrieval by ID and persistence.
