Strategies: the 11 chunking strategies, their options, and examples # Strategies > Eleven ways to split a document into chunks, and how to choose between them. A strategy decides where each chunk starts and ends. Doc-chunk has 11. They all use the same function, accept the same sources, and return the same result, so you can switch strategy by changing one option: ```ts import { chunkDocument } from "docchunk"; const { chunks } = await chunkDocument( { path: "handbook.pdf" }, { strategy: "sentence-window" }, ); ``` Without a `strategy` option, Doc-chunk uses [`structure`](./structure/). ## Which strategy to use [Section titled “Which strategy to use”](#which-strategy-to-use) Start with `structure`. It works well for most documents and most retrieval setups. Change it when you have a specific reason: | If you want | Use | | ------------------------------------------------------------------------------ | --------------------------------------- | | Good general-purpose chunks | [`structure`](./structure/) | | One chunk per section, such as one per article in a knowledge base | [`heading`](./heading/) | | One chunk per paragraph, list, or table, such as one per FAQ answer | [`paragraph`](./paragraph/) | | Small, precise chunks for search over prose | [`sentence`](./sentence/) | | Search on single sentences, with the sentences around each match for the model | [`sentence-window`](./sentence-window/) | | Small chunks for search, each linked to a larger chunk for the model | [`parent-child`](./parent-child/) | | Chunks at three or more sizes, or one chunk for every section and subsection | [`hierarchical`](./hierarchical/) | | The same behavior as the recursive character splitters in other libraries | [`recursive`](./recursive/) | | A simple baseline to compare the other strategies against | [`fixed`](./fixed/) | | Fixed-size chunks that share some text at each cut | [`fixed-overlap`](./fixed-overlap/) | | Overlapping windows that cover every part of the text more than once | [`sliding-window`](./sliding-window/) | [Compare strategies](./compare/) runs all 11 on the same document, so you can see the differences side by side. ## All strategies [Section titled “All strategies”](#all-strategies) | Strategy | Splits by | Follows structure | Default size | Output | | ----------------- | ------------------------------------------ | ----------------- | --------------------- | ----------------------------- | | `structure` | Whole blocks, packed up to `size` | Yes | 1,500 | Flat list | | `heading` | Sections | Yes | No limit | Flat list | | `paragraph` | Blocks | Yes | No limit | Flat list | | `sentence` | Sentences | Yes | No limit | Flat list | | `sentence-window` | Sentences | Yes | No limit | Flat list, with `contextText` | | `parent-child` | Whole blocks, at two sizes | Yes | 4,000 and 800 | Two levels | | `hierarchical` | Whole blocks at several sizes, or sections | Yes | 6,000, 1,500, and 400 | Several levels | | `recursive` | Separators, then sentences, then spaces | Partly | 1,500 | Flat list | | `fixed` | Character count | No | 1,500 | Flat list | | `fixed-overlap` | Character count, with overlap | No | 1,500 | Flat list | | `sliding-window` | Character count, moving by `step` | No | 1,500 | Flat list | A strategy that follows structure never puts two sections in one chunk, keeps tables, lists, and code blocks whole when they fit, and splits a block that is too large along its rows, items, lines, or sentences. `recursive` splits at headings and blank lines first, but it can join small sections into one chunk and doesn’t repeat table headers. The last three ignore structure and cut the text by length. All sizes are in characters. See [Sizes are in characters](../how-it-works/#sizes-are-in-characters). ## Options [Section titled “Options”](#options) Each strategy has its own options, listed on its page. Pass them next to `strategy`: ```ts const { chunks } = await chunkDocument( { path: "handbook.pdf" }, { strategy: "parent-child", parentSize: 3000, childSize: 600 }, ); ``` In TypeScript, the options type depends on `strategy`, so your editor suggests only the options of the strategy you chose, and flags the others. At runtime, an option the strategy doesn’t accept throws an `INVALID_OPTIONS` error. The options `metadata`, `documentId`, `headingPrefix`, and `signal` work with every strategy. See [Options every strategy accepts](../guides/chunk-document/#options-every-strategy-accepts). ## The example document [Section titled “The example document”](#the-example-document) Every strategy page runs the strategy on the same short file, `returns-policy.md`, so you can compare the results: returns-policy.md ```md # Returns policy You can return most items within 30 days of delivery. Items must be unused and in their original packaging. ## Start a return 1. Sign in and open **Orders**. 2. Choose the item you want to return. 3. Print the prepaid shipping label. ## Refunds We refund the original payment method within 5 business days of receiving the item. Shipping costs are not refunded. | Item | Refund | | --- | --- | | Unused item | Full price | | Opened item | 80% | ``` The file is 468 characters long, so the examples use small sizes to show how each strategy splits it. In real use, sizes of 500 to 2,000 characters are more common. # Structure > Packs whole blocks into chunks up to the size limit, never across a section. The default strategy. `structure` packs whole paragraphs, lists, tables, and code blocks into chunks of up to `size` characters, and starts a new chunk at every section. It’s the default strategy. ```ts const { chunks } = await chunkDocument({ path: "handbook.pdf" }); ``` ## When to use it [Section titled “When to use it”](#when-to-use-it) Use `structure` unless you have a reason to choose another strategy. It gives chunks that are about one topic, close to the size you ask for, and that don’t cut sentences, tables, or code in half. It works for manuals, reports, policies, notes, and most other documents. Consider another strategy when: * You want exactly one chunk per section, whatever its size: use [`heading`](../heading/). * You want small chunks for search and large chunks for the model: use [`parent-child`](../parent-child/). * The text has no structure at all, such as a raw transcript: `structure` still works, but [`sentence`](../sentence/) with a `size` gives the same result more directly. ## How it works [Section titled “How it works”](#how-it-works) 1. Each heading is joined to the block after it, so a heading never ends a chunk. 2. Blocks are added to a chunk in order until the next one doesn’t fit in `size`. Then a new chunk starts. 3. A new chunk always starts at a section heading: a heading at `headingLevel` or higher. Two sections never share a chunk. 4. A block larger than `size` is split along its structure: tables by rows, lists by items, code by lines, and prose by sentences. See [Blocks larger than the size limit](../../how-it-works/#blocks-larger-than-the-size-limit). 5. A chunk smaller than `minSize` is merged into the chunk before it, or else the chunk after it, if both are in the same section and the result fits in `size`. 6. With `overlapChars`, each chunk also starts with whole sentences from the end of the chunk before it, in the same section. ## Example [Section titled “Example”](#example) returns-policy.md ```md # Returns policy You can return most items within 30 days of delivery. Items must be unused and in their original packaging. ## Start a return 1. Sign in and open **Orders**. 2. Choose the item you want to return. 3. Print the prepaid shipping label. ## Refunds We refund the original payment method within 5 business days of receiving the item. Shipping costs are not refunded. | Item | Refund | | --- | --- | | Unused item | Full price | | Opened item | 80% | ``` With the default options, each section becomes one chunk: ```ts import { chunkDocument } from "docchunk"; const { chunks } = await chunkDocument({ path: "returns-policy.md" }); for (const chunk of chunks) { console.log(chunk.text); console.log("---"); } ``` ```txt # Returns policy You can return most items within 30 days of delivery. Items must be unused and in their original packaging. --- ## Start a return 1. Sign in and open **Orders**. 2. Choose the item you want to return. 3. Print the prepaid shipping label. --- ## Refunds We refund the original payment method within 5 business days of receiving the item. Shipping costs are not refunded. | Item | Refund | | --- | --- | | Unused item | Full price | | Opened item | 80% | --- ``` With a smaller `size`, the sections are split. The paragraphs are split by sentences, the list by items, and the table stays whole because it fits: ```ts import { chunkDocument } from "docchunk"; const { chunks } = await chunkDocument( { path: "returns-policy.md" }, { size: 100, minSize: 50 }, ); for (const chunk of chunks) { console.log(chunk.text); console.log("---"); } ``` ```txt # Returns policy You can return most items within 30 days of delivery. --- Items must be unused and in their original packaging. --- ## Start a return 1. Sign in and open **Orders**. 2. Choose the item you want to return. --- 3. Print the prepaid shipping label. --- ## Refunds We refund the original payment method within 5 business days of receiving the item. --- Shipping costs are not refunded. --- | Item | Refund | | --- | --- | | Unused item | Full price | | Opened item | 80% | --- ``` ## Options [Section titled “Options”](#options) | Option | Type | Default | Description | | -------------- | -------- | --------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | | `size` | `number` | `1500` | Maximum characters per chunk. A positive integer. | | `minSize` | `number` | `200`, or `size` if smaller | Chunks smaller than this are merged into a neighbor in the same section, when the result fits in `size`. A positive integer, at most `size`. | | `overlapChars` | `number` | `0` | Characters of whole sentences each chunk repeats from the end of the previous chunk in its section. An integer from 0, less than `size`. | | `headingLevel` | `number` | `3` | Headings at this level or higher start a new section. An integer from 1 to 6. | ## Good to know [Section titled “Good to know”](#good-to-know) * **Small sections stay small.** Sections are never merged, even when two would fit in one chunk. A document with many short sections gives many small chunks. To get fewer, larger chunks, lower `headingLevel`, for example to `2` or `1`, so that fewer headings start a section. * **`minSize` follows a small `size`.** When you set a `size` below 200 and no `minSize`, `minSize` becomes equal to `size`. A `minSize` you set yourself can’t be larger than `size`. * **Overlap can be shorter than `overlapChars`.** Overlap uses whole sentences, stays within the section, and never makes a chunk larger than `size`. If the last sentence of the previous chunk is longer than `overlapChars`, the chunk has no overlap. * **A heading stays with its content.** When a heading is followed by a block too large for one chunk, the heading starts the first piece of that block. The block is then split at `size` minus the heading’s length, so every piece still fits. * **A heading with no content of its own is a chunk.** A heading followed directly by another section heading, such as a title right before the first `##`, becomes a chunk that contains only the title. ## Related strategies [Section titled “Related strategies”](#related-strategies) * [`heading`](../heading/): one chunk per section, with no size limit by default. * [`paragraph`](../paragraph/): one chunk per block. * [`parent-child`](../parent-child/): `structure` at two sizes, with links between them. # Heading > One chunk per section. With a size limit, a larger section is split into packed blocks. `heading` gives one chunk per section. A section starts at a heading at `headingLevel` or higher, and includes everything up to the next such heading. ```ts const { chunks } = await chunkDocument( { path: "manual.docx" }, { strategy: "heading" }, ); ``` ## When to use it [Section titled “When to use it”](#when-to-use-it) Use `heading` when each section of your documents is a complete answer on its own, and you want to retrieve it whole. Examples are knowledge base articles, API reference pages, and manuals where each section covers one task. Don’t use it for documents with long sections, or with few headings, unless you set `size`. Without `size`, a long section becomes one long chunk, which is a poor match for specific questions and may exceed your embedding model’s limit. ## How it works [Section titled “How it works”](#how-it-works) 1. The document is divided into sections at every heading at `headingLevel` or higher. Deeper headings stay inside their section. 2. Each section becomes one chunk. Text before the first heading becomes a chunk of its own. 3. With `size`, a section larger than `size` is split into chunks of whole blocks, like [`structure`](../structure/) does. Small sections are not merged. ## Example [Section titled “Example”](#example) returns-policy.md ```md # Returns policy You can return most items within 30 days of delivery. Items must be unused and in their original packaging. ## Start a return 1. Sign in and open **Orders**. 2. Choose the item you want to return. 3. Print the prepaid shipping label. ## Refunds We refund the original payment method within 5 business days of receiving the item. Shipping costs are not refunded. | Item | Refund | | --- | --- | | Unused item | Full price | | Opened item | 80% | ``` Each `#` and `##` section becomes a chunk: ```ts import { chunkDocument } from "docchunk"; const { chunks } = await chunkDocument( { path: "returns-policy.md" }, { strategy: "heading" }, ); for (const chunk of chunks) { console.log(chunk.text); console.log("---"); } ``` ```txt # Returns policy You can return most items within 30 days of delivery. Items must be unused and in their original packaging. --- ## Start a return 1. Sign in and open **Orders**. 2. Choose the item you want to return. 3. Print the prepaid shipping label. --- ## Refunds We refund the original payment method within 5 business days of receiving the item. Shipping costs are not refunded. | Item | Refund | | --- | --- | | Unused item | Full price | | Opened item | 80% | --- ``` With `headingLevel: 1`, only `#` headings start a section, so the whole file is one chunk of 467 characters: ```ts import { chunkDocument } from "docchunk"; const { chunks } = await chunkDocument( { path: "returns-policy.md" }, { strategy: "heading", headingLevel: 1 }, ); console.log(chunks.length, chunks[0]?.charCount); ``` ```txt 1 467 ``` ## Options [Section titled “Options”](#options) | Option | Type | Default | Description | | -------------- | -------- | -------- | -------------------------------------------------------------------------------------- | | `size` | `number` | No limit | Maximum characters per chunk. Sections larger than this are split. A positive integer. | | `headingLevel` | `number` | `3` | Headings at this level or higher start a new section. An integer from 1 to 6. | ## Good to know [Section titled “Good to know”](#good-to-know) * **Large sections give a warning.** Without `size`, a chunk of more than 8,000 characters adds a `LARGE_CHUNK` warning to the result. Set `size` to split large sections. * **Headings with no text of their own become small chunks.** A title followed directly by a subheading, such as `# Guide` right before `## Setup`, becomes a chunk that contains only the title. * **With `size`, `heading` and `structure` are close.** The difference is that `heading` doesn’t merge small chunks, and has no overlap. ## Related strategies [Section titled “Related strategies”](#related-strategies) * [`structure`](../structure/): packs sections into chunks of a set size. * [`hierarchical`](../hierarchical/) with `by: "heading"`: a chunk for every section and subsection, nested. # Paragraph > One chunk per block, with each heading kept with the block after it. `paragraph` gives one chunk per block: a paragraph, a list, a table, a code block, or a block quote. Each heading is joined to the block after it. ```ts const { chunks } = await chunkDocument( { path: "faq.md" }, { strategy: "paragraph" }, ); ``` ## When to use it [Section titled “When to use it”](#when-to-use-it) Use `paragraph` when each paragraph is a self-contained answer, such as FAQ entries, glossaries, or release notes where each paragraph describes one change. Don’t use it for long-form prose, where a paragraph often depends on the ones around it. Chunks of one paragraph each can then lack the context needed to match a question. [`structure`](../structure/) packs related paragraphs together instead. ## How it works [Section titled “How it works”](#how-it-works) 1. Each block becomes one chunk. A whole list or a whole table counts as one block. 2. A heading is joined to the block after it, so it isn’t a chunk of its own. 3. With `size`, consecutive blocks in the same section are packed together up to `size`, and a block larger than `size` is split along its structure. 4. With `minSize`, a chunk smaller than `minSize` is merged into its neighbor in the same section. ## Example [Section titled “Example”](#example) returns-policy.md ```md # Returns policy You can return most items within 30 days of delivery. Items must be unused and in their original packaging. ## Start a return 1. Sign in and open **Orders**. 2. Choose the item you want to return. 3. Print the prepaid shipping label. ## Refunds We refund the original payment method within 5 business days of receiving the item. Shipping costs are not refunded. | Item | Refund | | --- | --- | | Unused item | Full price | | Opened item | 80% | ``` Each heading is joined to its paragraph or list, and the table is a chunk of its own: ```ts import { chunkDocument } from "docchunk"; const { chunks } = await chunkDocument( { path: "returns-policy.md" }, { strategy: "paragraph" }, ); for (const chunk of chunks) { console.log(chunk.text); console.log("---"); } ``` ```txt # Returns policy You can return most items within 30 days of delivery. Items must be unused and in their original packaging. --- ## Start a return 1. Sign in and open **Orders**. 2. Choose the item you want to return. 3. Print the prepaid shipping label. --- ## Refunds We refund the original payment method within 5 business days of receiving the item. Shipping costs are not refunded. --- | Item | Refund | | --- | --- | | Unused item | Full price | | Opened item | 80% | --- ``` ## Options [Section titled “Options”](#options) | Option | Type | Default | Description | | -------------- | -------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `size` | `number` | No limit | Maximum characters per chunk. With a size, consecutive blocks are packed together. A positive integer. | | `minSize` | `number` | `1` | Chunks smaller than this are merged into a neighbor in the same section, when the result fits in `size`. The default merges nothing. A positive integer, at most `size`. | | `overlapChars` | `number` | `0` | Characters of whole sentences each chunk repeats from the end of the previous chunk in its section. An integer from 0, less than `size`. | ## Good to know [Section titled “Good to know”](#good-to-know) * **A long list or table is one chunk.** Without `size`, nothing is split. A chunk of more than 8,000 characters adds a `LARGE_CHUNK` warning. Set `size` to split large blocks. * **`minSize` works without `size`.** With no size limit, every chunk smaller than `minSize` is merged into a neighbor in the same section. Use it to join very short paragraphs, such as one-line answers, to the paragraph next to them. * **With `size`, `paragraph` behaves like `structure`,** except that `minSize` defaults to 1 instead of 200. ## Related strategies [Section titled “Related strategies”](#related-strategies) * [`structure`](../structure/): packs blocks together up to a size. * [`sentence`](../sentence/): one chunk per sentence. # Sentence > One chunk per sentence, or consecutive sentences in the same section packed up to a size limit. `sentence` gives one chunk per sentence. With `size`, it packs consecutive sentences of the same section into chunks of up to `size` characters. ```ts const { chunks } = await chunkDocument( { path: "transcript.txt" }, { strategy: "sentence" }, ); ``` ## When to use it [Section titled “When to use it”](#when-to-use-it) Use `sentence` without `size` for very precise search, where each result should be one statement. Use it with `size` for text without much structure, such as transcripts, emails, or articles written as long runs of paragraphs, when you want chunks that always end at the end of a sentence. One-sentence chunks often lack context for the model. If you search on sentences but want to send more text to the model, use [`sentence-window`](../sentence-window/). ## How it works [Section titled “How it works”](#how-it-works) 1. The document is split into sentences with the JavaScript `Intl.Segmenter` API. Each list item gives at least one sentence, and a whole table or code block counts as one sentence. 2. Headings are not sentences, so they aren’t in any chunk’s text. Each chunk’s `headingPath` still lists them. 3. Without `size`, each sentence is a chunk. With `size`, consecutive sentences in the same section are packed together up to `size`. 4. A sentence larger than `size` is split at spaces. A table or code block larger than `size` is split by rows or lines. ## Example [Section titled “Example”](#example) returns-policy.md ```md # Returns policy You can return most items within 30 days of delivery. Items must be unused and in their original packaging. ## Start a return 1. Sign in and open **Orders**. 2. Choose the item you want to return. 3. Print the prepaid shipping label. ## Refunds We refund the original payment method within 5 business days of receiving the item. Shipping costs are not refunded. | Item | Refund | | --- | --- | | Unused item | Full price | | Opened item | 80% | ``` Each sentence, list item, and the table become chunks. The headings are left out: ```ts import { chunkDocument } from "docchunk"; const { chunks } = await chunkDocument( { path: "returns-policy.md" }, { strategy: "sentence" }, ); for (const chunk of chunks) { console.log(chunk.text); console.log("---"); } ``` ```txt You can return most items within 30 days of delivery. --- Items must be unused and in their original packaging. --- 1. Sign in and open **Orders**. --- 2. Choose the item you want to return. --- 3. Print the prepaid shipping label. --- We refund the original payment method within 5 business days of receiving the item. --- Shipping costs are not refunded. --- | Item | Refund | | --- | --- | | Unused item | Full price | | Opened item | 80% | --- ``` With `size: 150`, the sentences of each section are packed together: ```ts import { chunkDocument } from "docchunk"; const { chunks } = await chunkDocument( { path: "returns-policy.md" }, { strategy: "sentence", size: 150 }, ); for (const chunk of chunks) { console.log(chunk.text); console.log("---"); } ``` ```txt You can return most items within 30 days of delivery. Items must be unused and in their original packaging. --- 1. Sign in and open **Orders**. 2. Choose the item you want to return. 3. Print the prepaid shipping label. --- We refund the original payment method within 5 business days of receiving the item. Shipping costs are not refunded. --- | Item | Refund | | --- | --- | | Unused item | Full price | | Opened item | 80% | --- ``` ## Options [Section titled “Options”](#options) | Option | Type | Default | Description | | -------------- | -------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `size` | `number` | No limit | Maximum characters per chunk. With a size, consecutive sentences are packed together. A positive integer. | | `minSize` | `number` | `1` | Chunks smaller than this are merged into a neighbor in the same section, when the result fits in `size`. The default merges nothing. A positive integer, at most `size`. | | `overlapChars` | `number` | `0` | Characters of whole sentences each chunk repeats from the end of the previous chunk in its section. An integer from 0, less than `size`. | ## Good to know [Section titled “Good to know”](#good-to-know) * **Abbreviations can end a sentence.** `Intl.Segmenter` sometimes ends a sentence after an abbreviation such as “Dr.” or “e.g.”. Setting `size` or `minSize` hides most of these splits, because short pieces are packed or merged with their neighbors. * **Headings aren’t in the text.** Use `headingPath`, or the `headingPrefix` option, to keep the heading context. * **Sentences never cross sections.** Packing and overlap stay within one section. ## Related strategies [Section titled “Related strategies”](#related-strategies) * [`sentence-window`](../sentence-window/): one sentence per chunk, with the sentences around it as context. * [`paragraph`](../paragraph/): one chunk per block. # Sentence window > One chunk per sentence, with the sentences around it in the same section as context. `sentence-window` gives one chunk per sentence, like [`sentence`](../sentence/). Each chunk also has a `contextText` field with the sentences around it: `windowSize` sentences before and after, within the same section. ```ts const { chunks } = await chunkDocument( { path: "handbook.pdf" }, { strategy: "sentence-window" }, ); ``` ## When to use it [Section titled “When to use it”](#when-to-use-it) Use `sentence-window` when you want precise search and enough context for the model to answer. Embed each chunk’s `text`, so a search matches single sentences. When a chunk matches, send its `contextText` to the model instead of its `text`. It works best with prose. For documents made mostly of tables or code, where one “sentence” is already a whole block, [`structure`](../structure/) is simpler. ## How it works [Section titled “How it works”](#how-it-works) 1. The document is split into sentences, as in [`sentence`](../sentence/). A whole table or code block counts as one sentence, and headings are left out. 2. Each sentence becomes a chunk, and its `text` is that sentence. 3. `contextText` is the text from `windowSize` sentences before the chunk’s sentence to `windowSize` sentences after it. The window stops at the edges of the section, so the context never includes another section. ## Example [Section titled “Example”](#example) returns-policy.md ```md # Returns policy You can return most items within 30 days of delivery. Items must be unused and in their original packaging. ## Start a return 1. Sign in and open **Orders**. 2. Choose the item you want to return. 3. Print the prepaid shipping label. ## Refunds We refund the original payment method within 5 business days of receiving the item. Shipping costs are not refunded. | Item | Refund | | --- | --- | | Unused item | Full price | | Opened item | 80% | ``` With `windowSize: 1`, each chunk’s context is the sentence before it, the sentence itself, and the sentence after it. Here are the last three chunks: ```ts import { chunkDocument } from "docchunk"; const { chunks } = await chunkDocument( { path: "returns-policy.md" }, { strategy: "sentence-window", windowSize: 1 }, ); for (const chunk of chunks.slice(5)) { console.log("text:", chunk.text); console.log("context:", chunk.contextText); console.log("---"); } ``` ```txt text: We refund the original payment method within 5 business days of receiving the item. context: We refund the original payment method within 5 business days of receiving the item. Shipping costs are not refunded. --- text: Shipping costs are not refunded. context: We refund the original payment method within 5 business days of receiving the item. Shipping costs are not refunded. | Item | Refund | | --- | --- | | Unused item | Full price | | Opened item | 80% | --- text: | Item | Refund | | --- | --- | | Unused item | Full price | | Opened item | 80% | context: Shipping costs are not refunded. | Item | Refund | | --- | --- | | Unused item | Full price | | Opened item | 80% | --- ``` The first of these chunks has nothing before it in the *Refunds* section, so its context starts with the sentence itself. ## Options [Section titled “Options”](#options) | Option | Type | Default | Description | | ------------ | -------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------- | | `windowSize` | `number` | `3` | Sentences on each side of the chunk’s sentence that go into `contextText`. An integer from 0. With `0`, `contextText` is the same as `text`. | ## Good to know [Section titled “Good to know”](#good-to-know) * **`contextText` has no size limit.** It grows with `windowSize`, and a window that includes a large table includes the whole table. Choose `windowSize` with your model’s context in mind. * **Only `text` counts for size.** `charCount` and `contentHash` describe `text`, not `contextText`. * **Use `headingPath` for the headings.** Headings are not part of `text` or `contextText`. ## Related strategies [Section titled “Related strategies”](#related-strategies) * [`sentence`](../sentence/): the same chunks, without `contextText`. * [`parent-child`](../parent-child/): the same idea at a larger scale: small chunks for search, each linked to a larger chunk for the model. # Parent-child > Small chunks for search, each linked to a larger parent chunk that gives context. `parent-child` gives chunks at two sizes: large parent chunks, and small child chunks inside each parent. Each child links to its parent, and each parent lists its children. ```ts const { chunks } = await chunkDocument( { path: "policy.pdf" }, { strategy: "parent-child" }, ); ``` ## When to use it [Section titled “When to use it”](#when-to-use-it) Small chunks give precise search results, but often don’t contain enough for the model to answer. Large chunks give the model context, but their embeddings are less precise. `parent-child` gives you both: embed the children, and when a child matches a question, send its parent to the model. If you need more than two sizes, use [`hierarchical`](../hierarchical/). If you want context at the level of sentences rather than blocks, use [`sentence-window`](../sentence-window/). ## How it works [Section titled “How it works”](#how-it-works) 1. The parents are made with [`structure`](../structure/) at `parentSize`. They never cross a section. 2. Each parent is split again with `structure` at `childSize`. The children always lie inside their parent. 3. Parents have `level: 0` and a `childIds` list. Children have `level: 1` and a `parentId`. 4. All chunks are returned in one list, in document order, with each parent before its children. ## Example [Section titled “Example”](#example) returns-policy.md ```md # Returns policy You can return most items within 30 days of delivery. Items must be unused and in their original packaging. ## Start a return 1. Sign in and open **Orders**. 2. Choose the item you want to return. 3. Print the prepaid shipping label. ## Refunds We refund the original payment method within 5 business days of receiving the item. Shipping costs are not refunded. | Item | Refund | | --- | --- | | Unused item | Full price | | Opened item | 80% | ``` ```ts import { chunkDocument } from "docchunk"; const { chunks } = await chunkDocument( { path: "returns-policy.md" }, { strategy: "parent-child", parentSize: 300, childSize: 100 }, ); for (const chunk of chunks) { const indent = " ".repeat(chunk.level ?? 0); const firstLine = chunk.text.split("\n")[0]; console.log(`${indent}level ${chunk.level}, ${chunk.charCount} chars: ${firstLine}`); } ``` ```txt level 0, 125 chars: # Returns policy level 1, 71 chars: # Returns policy level 1, 53 chars: Items must be unused and in their original packaging. level 0, 126 chars: ## Start a return level 1, 89 chars: ## Start a return level 1, 36 chars: 3. Print the prepaid shipping label. level 0, 212 chars: ## Refunds level 1, 95 chars: ## Refunds level 1, 32 chars: Shipping costs are not refunded. level 1, 82 chars: | Item | Refund | ``` Each section is one parent. The *Refunds* parent has three children: the heading with the first sentence, the second sentence, and the table. ## Use the parents and children [Section titled “Use the parents and children”](#use-the-parents-and-children) Embed only the children, and keep a way to find each chunk by its `id`: ```ts import { chunkDocument } from "docchunk"; const { chunks } = await chunkDocument( { path: "policy.pdf" }, { strategy: "parent-child" }, ); const children = chunks.filter((chunk) => chunk.level === 1); const chunksById = new Map(chunks.map((chunk) => [chunk.id, chunk])); // Embed and store `children`. When a search returns a child, // look up its parent and send the parent's text to the model: // const parent = chunksById.get(child.parentId ?? ""); ``` In a vector database, store each child’s `parentId` in its metadata, and store the parents’ text somewhere you can look up by id, such as a key-value store or another table. ## Options [Section titled “Options”](#options) | Option | Type | Default | Description | | ------------ | -------- | ------- | ---------------------------------------------------------------------------------- | | `parentSize` | `number` | `4000` | Maximum characters per parent chunk. A positive integer, larger than `childSize`. | | `childSize` | `number` | `800` | Maximum characters per child chunk. A positive integer, smaller than `parentSize`. | ## Good to know [Section titled “Good to know”](#good-to-know) * **A parent can have a single child with the same text.** When a parent is no larger than `childSize`, its only child is a copy of it. Both have different `id`s, because their levels differ. * **Parents follow sections.** A parent never spans two sections, so a document with short sections has parents much smaller than `parentSize`. * **Children use a `minSize` of 200,** or `childSize` if that is smaller, so very short children are merged with their neighbors. * **`buildChunkTree` turns the list into a tree.** See [`buildChunkTree`](../../reference/build-chunk-tree/). ## Related strategies [Section titled “Related strategies”](#related-strategies) * [`hierarchical`](../hierarchical/): the same idea with any number of levels, or following the headings. * [`sentence-window`](../sentence-window/): small chunks with surrounding context, at the level of sentences. # Hierarchical > Nested chunks at several sizes, or chunks that follow the heading tree. `hierarchical` gives nested chunks: large chunks, the chunks inside them, the chunks inside those, and so on. It builds the levels in one of two ways: by size, or by heading. ```ts const { chunks } = await chunkDocument( { path: "handbook.pdf" }, { strategy: "hierarchical", levels: [6000, 1500, 400] }, ); ``` ## When to use it [Section titled “When to use it”](#when-to-use-it) Use `hierarchical` by size when you want more than the two levels of [`parent-child`](../parent-child/), for example to search small chunks and then widen the context step by step. Use `hierarchical` by heading when you want a chunk for every section and every subsection, so you can retrieve a whole chapter, one of its sections, or one subsection. This suits long documents with a clear outline, such as manuals and specifications. ## How it works [Section titled “How it works”](#how-it-works) ### By size [Section titled “By size”](#by-size) With `by: "size"`, the default, `levels` lists the maximum size of each level, largest first. 1. Level 0 is made with [`structure`](../structure/) at the first size. 2. Each chunk of level 0 is split with `structure` at the second size, giving level 1. Each chunk of level 1 is split at the third size, and so on. 3. Every chunk below level 0 has a `parentId`, and every chunk with children has `childIds`. `parent-child` is the same as `hierarchical` by size with two levels. ### By heading [Section titled “By heading”](#by-heading) With `by: "heading"`, the levels follow the document’s headings. 1. Every heading at `headingLevel` or higher starts a section. Each section becomes a chunk that includes its subsections. 2. A section’s level is how deeply it is nested: level 0 for the outermost sections, 1 for the sections inside them, and so on. Text before the first heading is a chunk at level 0. 3. A section with no subsections that is larger than `leafSize` gets children: it is split with `structure` at `leafSize`, one level deeper. ## Example [Section titled “Example”](#example) returns-policy.md ```md # Returns policy You can return most items within 30 days of delivery. Items must be unused and in their original packaging. ## Start a return 1. Sign in and open **Orders**. 2. Choose the item you want to return. 3. Print the prepaid shipping label. ## Refunds We refund the original payment method within 5 business days of receiving the item. Shipping costs are not refunded. | Item | Refund | | --- | --- | | Unused item | Full price | | Opened item | 80% | ``` By heading, the `#` section contains the whole document, the `##` sections are inside it, and the *Refunds* section is larger than `leafSize`, so it’s split again: ```ts import { chunkDocument } from "docchunk"; const { chunks } = await chunkDocument( { path: "returns-policy.md" }, { strategy: "hierarchical", by: "heading", leafSize: 150 }, ); for (const chunk of chunks) { const indent = " ".repeat(chunk.level ?? 0); const firstLine = chunk.text.split("\n")[0]; console.log(`${indent}level ${chunk.level}, ${chunk.charCount} chars: ${firstLine}`); } ``` ```txt level 0, 467 chars: # Returns policy level 1, 126 chars: ## Start a return level 1, 212 chars: ## Refunds level 2, 128 chars: ## Refunds level 2, 82 chars: | Item | Refund | ``` By size, with three levels: ```ts import { chunkDocument } from "docchunk"; const { chunks } = await chunkDocument( { path: "returns-policy.md" }, { strategy: "hierarchical", levels: [400, 150, 100] }, ); for (const chunk of chunks) { const indent = " ".repeat(chunk.level ?? 0); const firstLine = chunk.text.split("\n")[0]; console.log(`${indent}level ${chunk.level}, ${chunk.charCount} chars: ${firstLine}`); } ``` ```txt level 0, 125 chars: # Returns policy level 1, 125 chars: # Returns policy level 2, 71 chars: # Returns policy level 2, 53 chars: Items must be unused and in their original packaging. level 0, 126 chars: ## Start a return level 1, 126 chars: ## Start a return level 2, 89 chars: ## Start a return level 2, 36 chars: 3. Print the prepaid shipping label. level 0, 212 chars: ## Refunds level 1, 128 chars: ## Refunds level 2, 95 chars: ## Refunds level 2, 32 chars: Shipping costs are not refunded. level 1, 82 chars: | Item | Refund | level 2, 82 chars: | Item | Refund | ``` ## Options [Section titled “Options”](#options) | Option | Type | Default | Description | | -------------- | ----------------------- | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `by` | `"size"` or `"heading"` | `"size"` | How the levels are built. | | `levels` | `number[]` | `[6000, 1500, 400]` | Maximum characters per chunk at each level, largest first. Used with `by: "size"`. A non-empty array of positive integers, each smaller than the one before. | | `headingLevel` | `number` | `3` | Headings at this level or higher start a new section. An integer from 1 to 6. | | `leafSize` | `number` | `1500` | Maximum characters per chunk when a section without subsections is split. Used with `by: "heading"`. A positive integer. | ## Good to know [Section titled “Good to know”](#good-to-know) * **A chunk can have a single child with the same text.** When a chunk already fits the next level’s size, its only child is a copy of it, one level deeper. * **By heading, sections have no size limit.** Only sections without subsections are split, at `leafSize`. A large section with subsections stays whole at its own level, and a chunk of more than 8,000 characters adds a `LARGE_CHUNK` warning. * **Chunks are sorted by position, then level.** Each chunk comes before the chunks inside it. * **`buildChunkTree` turns the list into a tree.** See [`buildChunkTree`](../../reference/build-chunk-tree/). ## Related strategies [Section titled “Related strategies”](#related-strategies) * [`parent-child`](../parent-child/): two levels by size, with simpler options. * [`heading`](../heading/): one flat chunk per section. # Recursive > Splits on separators, then sentences, then spaces, until every piece fits the size limit. `recursive` splits the text at a list of separators, from headings to blank lines to line breaks, then at sentences and spaces, until every piece fits in `size`. Then it joins neighboring pieces back together, up to `size`. ```ts const { chunks } = await chunkDocument( { path: "notes.md" }, { strategy: "recursive" }, ); ``` ## When to use it [Section titled “When to use it”](#when-to-use-it) Use `recursive` when you are moving from another library’s recursive character splitter, such as LangChain’s `RecursiveCharacterTextSplitter`, and want similar chunks. For new projects, [`structure`](../structure/) usually gives better chunks: it never joins two sections, and it repeats table headers and code fences when it splits them. ## How it works [Section titled “How it works”](#how-it-works) 1. If the text fits in `size`, it’s one chunk. 2. Otherwise, the text is split at the first separator in `separators` that occurs in it. Each separator stays at the start of the piece after the split. 3. Neighboring pieces are joined back together, as long as the result fits in `size`. 4. A piece that is still larger than `size` is split again with the next separator. After the separators come sentence boundaries, then spaces, and finally a cut at exactly `size` characters. The default separators, in order, are a line starting with `# `, `## `, `### `, or `#### `, then a blank line, then a line break. ## Example [Section titled “Example”](#example) returns-policy.md ```md # Returns policy You can return most items within 30 days of delivery. Items must be unused and in their original packaging. ## Start a return 1. Sign in and open **Orders**. 2. Choose the item you want to return. 3. Print the prepaid shipping label. ## Refunds We refund the original payment method within 5 business days of receiving the item. Shipping costs are not refunded. | Item | Refund | | --- | --- | | Unused item | Full price | | Opened item | 80% | ``` ```ts import { chunkDocument } from "docchunk"; const { chunks } = await chunkDocument( { path: "returns-policy.md" }, { strategy: "recursive", size: 100 }, ); for (const chunk of chunks) { console.log(chunk.text); console.log("---"); } ``` ```txt # Returns policy --- You can return most items within 30 days of delivery. --- Items must be unused and in their original packaging. --- ## Start a return --- 1. Sign in and open **Orders**. 2. Choose the item you want to return. --- 3. Print the prepaid shipping label. --- ## Refunds --- We refund the original payment method within 5 business days of receiving the item. --- Shipping costs are not refunded. --- | Item | Refund | | --- | --- | | Unused item | Full price | | Opened item | 80% | --- ``` The document was split at headings, then at blank lines, then at sentences. Each heading ended up on its own, because joining it to the paragraph after it would go over `size`. ## Options [Section titled “Options”](#options) | Option | Type | Default | Description | | -------------- | ---------- | ------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------- | | `size` | `number` | `1500` | Maximum characters per chunk. A positive integer. | | `overlapChars` | `number` | `0` | Characters of whole pieces each chunk repeats from the end of the previous one. An integer from 0, less than `size`. | | `separators` | `string[]` | `["\n# ", "\n## ", "\n### ", "\n#### ", "\n\n", "\n"]` | Separators tried in order, before sentences, spaces, and a cut at `size`. An array of non-empty strings. | ## Good to know [Section titled “Good to know”](#good-to-know) * **Sections can share a chunk.** Pieces are joined whenever they fit, so small sections are joined together, unlike in `structure`. * **Tables and code blocks are split by lines.** A large table is split at line breaks without repeating its header, and a large code block without repeating its fences. * **Headings can end up alone,** as in the example, when the text after them is too large to join. * **Custom separators.** To split plain text at a different marker, such as a line of dashes, pass your own list: `separators: ["\n---\n", "\n\n", "\n"]`. ## Related strategies [Section titled “Related strategies”](#related-strategies) * [`structure`](../structure/): splits by the parsed structure instead of separator strings. * [`sentence`](../sentence/) with `size`: packs whole sentences. # Fixed > Cuts the text every size characters, ignoring the document's structure. `fixed` cuts the document’s Markdown into pieces of `size` characters, from start to end. It ignores headings, paragraphs, tables, and every other part of the structure. ```ts const { chunks } = await chunkDocument( { path: "notes.txt" }, { strategy: "fixed", size: 1000 }, ); ``` ## When to use it [Section titled “When to use it”](#when-to-use-it) Use `fixed` as a baseline: chunk your documents with `fixed` and with another strategy, and compare the retrieval quality. It’s also fine for text with no structure at all, where every part is equally important, such as logs. Don’t use it for documents with headings, lists, or tables. Its chunks cut through sentences, list items, and table rows, and mix the end of one section with the start of the next. ## How it works [Section titled “How it works”](#how-it-works) 1. The first chunk is the first `size` characters of `document.markdown`, the next chunk the following `size` characters, and so on. 2. With `boundary: "word"`, the default, a cut that falls inside a word moves back to just after the last space or line break within the last 10% of the chunk. If there’s none, the cut stays at `size`. 3. With `boundary: "char"`, every cut is at exactly `size` characters. ## Example [Section titled “Example”](#example) returns-policy.md ```md # Returns policy You can return most items within 30 days of delivery. Items must be unused and in their original packaging. ## Start a return 1. Sign in and open **Orders**. 2. Choose the item you want to return. 3. Print the prepaid shipping label. ## Refunds We refund the original payment method within 5 business days of receiving the item. Shipping costs are not refunded. | Item | Refund | | --- | --- | | Unused item | Full price | | Opened item | 80% | ``` ```ts import { chunkDocument } from "docchunk"; const { chunks } = await chunkDocument( { path: "returns-policy.md" }, { strategy: "fixed", size: 200 }, ); for (const chunk of chunks) { console.log(chunk.text); console.log("---"); } ``` ```txt # Returns policy You can return most items within 30 days of delivery. Items must be unused and in their original packaging. ## Start a return 1. Sign in and open **Orders**. 2. Choose the item you --- want to return. 3. Print the prepaid shipping label. ## Refunds We refund the original payment method within 5 business days of receiving the item. Shipping costs are not refunded. | Item | Refund --- | | --- | --- | | Unused item | Full price | | Opened item | 80% | --- ``` The first cut falls in the middle of a list item, and the second in the middle of the table’s header row. ## Options [Section titled “Options”](#options) | Option | Type | Default | Description | | ---------- | -------------------- | -------- | ------------------------------------------------------------------------------------------------ | | `size` | `number` | `1500` | Maximum characters per chunk. A positive integer. | | `boundary` | `"word"` or `"char"` | `"word"` | `"word"` moves a cut back to a space near the end of the chunk. `"char"` cuts at exactly `size`. | ## Good to know [Section titled “Good to know”](#good-to-know) * **Chunks can be shorter than `size`.** Word boundaries move cuts back, and spaces and line breaks at the start and end of each chunk are removed. * **Emoji are never cut in half.** A cut never falls inside a character that JavaScript stores as two code units, such as an emoji. * **`headingPath` still works.** Each chunk lists the headings above its start, even though the cuts ignore them. ## Related strategies [Section titled “Related strategies”](#related-strategies) * [`fixed-overlap`](../fixed-overlap/): the same cuts, with some text repeated between neighboring chunks. * [`sliding-window`](../sliding-window/): windows that move by a set step. * [`structure`](../structure/): chunks of a set size that follow the structure. # Fixed overlap > Like fixed, but consecutive chunks share a set number of characters. `fixed-overlap` cuts the text into pieces of `size` characters, like [`fixed`](../fixed/), but each chunk starts `overlapChars` characters before the previous one ended. Text near each cut appears in two chunks. ```ts const { chunks } = await chunkDocument( { path: "notes.txt" }, { strategy: "fixed-overlap", size: 1000, overlapChars: 150 }, ); ``` ## When to use it [Section titled “When to use it”](#when-to-use-it) Use `fixed-overlap` for text without structure when a sentence cut in half by `fixed` would be lost. With overlap, the text on both sides of every cut is complete in at least one chunk, as long as it’s shorter than `overlapChars`. For documents with structure, [`structure`](../structure/) with `overlapChars` gives overlap of whole sentences instead. ## How it works [Section titled “How it works”](#how-it-works) 1. The first chunk is cut as in `fixed`: at `size` characters, moved back to a word boundary with `boundary: "word"`. 2. Each following chunk starts `overlapChars` characters before the end of the previous chunk, and is cut the same way. 3. `size` includes the overlap: every chunk is at most `size` characters long. ## Example [Section titled “Example”](#example) returns-policy.md ```md # Returns policy You can return most items within 30 days of delivery. Items must be unused and in their original packaging. ## Start a return 1. Sign in and open **Orders**. 2. Choose the item you want to return. 3. Print the prepaid shipping label. ## Refunds We refund the original payment method within 5 business days of receiving the item. Shipping costs are not refunded. | Item | Refund | | --- | --- | | Unused item | Full price | | Opened item | 80% | ``` ```ts import { chunkDocument } from "docchunk"; const { chunks } = await chunkDocument( { path: "returns-policy.md" }, { strategy: "fixed-overlap", size: 200, overlapChars: 50 }, ); for (const chunk of chunks) { console.log(chunk.text); console.log("---"); } ``` ```txt # Returns policy You can return most items within 30 days of delivery. Items must be unused and in their original packaging. ## Start a return 1. Sign in and open **Orders**. 2. Choose the item you --- ign in and open **Orders**. 2. Choose the item you want to return. 3. Print the prepaid shipping label. ## Refunds We refund the original payment method within 5 business days of receiving the item. --- thod within 5 business days of receiving the item. Shipping costs are not refunded. | Item | Refund | | --- | --- | | Unused item | Full price | | Opened item | 80% | --- ``` Each chunk after the first repeats the last 50 characters of the chunk before it. ## Options [Section titled “Options”](#options) | Option | Type | Default | Description | | -------------- | -------------------- | -------- | ---------------------------------------------------------------------------------------------------- | | `size` | `number` | `1500` | Maximum characters per chunk, including the overlap. A positive integer. | | `overlapChars` | `number` | `200` | Characters each chunk repeats from the end of the previous one. An integer from 0, less than `size`. | | `boundary` | `"word"` or `"char"` | `"word"` | `"word"` moves a cut back to a space near the end of the chunk. `"char"` cuts at exactly `size`. | ## Good to know [Section titled “Good to know”](#good-to-know) * **Chunks can start in the middle of a word.** `boundary` moves where each chunk ends, but each chunk starts exactly `overlapChars` before the previous end, as in the example above. * **More overlap means more chunks.** Each chunk adds `size - overlapChars` new characters, so an overlap of half the size roughly doubles the number of chunks. * **With `overlapChars: 0`,** `fixed-overlap` gives the same chunks as `fixed`. ## Related strategies [Section titled “Related strategies”](#related-strategies) * [`fixed`](../fixed/): the same cuts, without overlap. * [`sliding-window`](../sliding-window/): the same strategy, set by the step between chunks instead of the overlap. # Sliding window > A window of size characters that moves forward step characters at a time. `sliding-window` moves a window of `size` characters through the text, `step` characters at a time. Each position of the window is a chunk. ```ts const { chunks } = await chunkDocument( { path: "notes.txt" }, { strategy: "sliding-window", size: 1000, step: 500 }, ); ``` ## When to use it [Section titled “When to use it”](#when-to-use-it) Use `sliding-window` for text without structure when you want every part of the text to appear in more than one chunk, so that a passage is complete in at least one of them wherever it falls. With `step` at half of `size`, the default, most characters are in two chunks. For documents with structure, prefer [`structure`](../structure/). For fewer, less overlapping chunks, use [`fixed-overlap`](../fixed-overlap/) with a small overlap. ## How it works [Section titled “How it works”](#how-it-works) `sliding-window` is [`fixed-overlap`](../fixed-overlap/) with an overlap of `size - step`: 1. The first chunk is the first `size` characters, moved back to a word boundary with `boundary: "word"`. 2. Each following chunk starts `size - step` characters before the end of the previous one, which is about `step` characters after the previous start. ## Example [Section titled “Example”](#example) returns-policy.md ```md # Returns policy You can return most items within 30 days of delivery. Items must be unused and in their original packaging. ## Start a return 1. Sign in and open **Orders**. 2. Choose the item you want to return. 3. Print the prepaid shipping label. ## Refunds We refund the original payment method within 5 business days of receiving the item. Shipping costs are not refunded. | Item | Refund | | --- | --- | | Unused item | Full price | | Opened item | 80% | ``` ```ts import { chunkDocument } from "docchunk"; const { chunks } = await chunkDocument( { path: "returns-policy.md" }, { strategy: "sliding-window", size: 200, step: 100 }, ); for (const chunk of chunks) { console.log(chunk.text); console.log("---"); } ``` ```txt # Returns policy You can return most items within 30 days of delivery. Items must be unused and in their original packaging. ## Start a return 1. Sign in and open **Orders**. 2. Choose the item you --- their original packaging. ## Start a return 1. Sign in and open **Orders**. 2. Choose the item you want to return. 3. Print the prepaid shipping label. ## Refunds We refund the original payment --- ou want to return. 3. Print the prepaid shipping label. ## Refunds We refund the original payment method within 5 business days of receiving the item. Shipping costs are not refunded. | Item | --- ent method within 5 business days of receiving the item. Shipping costs are not refunded. | Item | Refund | | --- | --- | | Unused item | Full price | | Opened item | 80% | --- ``` ## Options [Section titled “Options”](#options) | Option | Type | Default | Description | | ---------- | -------------------- | -------- | ------------------------------------------------------------------------------------------------ | | `size` | `number` | `1500` | Characters in each window. A positive integer. | | `step` | `number` | `750` | Characters the window moves forward each time. A positive integer, at most `size`. | | `boundary` | `"word"` or `"char"` | `"word"` | `"word"` moves a cut back to a space near the end of the chunk. `"char"` cuts at exactly `size`. | ## Good to know [Section titled “Good to know”](#good-to-know) * **The step isn’t exact with word boundaries.** When a window’s end moves back to a space, the next window starts earlier by the same amount. * **Chunks can start in the middle of a word,** as in `fixed-overlap`. * **With `step` equal to `size`,** windows don’t overlap, and the result is the same as `fixed`. ## Related strategies [Section titled “Related strategies”](#related-strategies) * [`fixed-overlap`](../fixed-overlap/): the same strategy, set by the overlap instead of the step. * [`fixed`](../fixed/): windows with no overlap. # Compare strategies > All 11 strategies run on the same document, side by side. This page runs every strategy on the same short document, so you can see where each one puts its chunk boundaries. The size-based strategies use sizes of 100 to 400 characters, because the document is small. ## The document [Section titled “The document”](#the-document) returns-policy.md ```md # Returns policy You can return most items within 30 days of delivery. Items must be unused and in their original packaging. ## Start a return 1. Sign in and open **Orders**. 2. Choose the item you want to return. 3. Print the prepaid shipping label. ## Refunds We refund the original payment method within 5 business days of receiving the item. Shipping costs are not refunded. | Item | Refund | | --- | --- | | Unused item | Full price | | Opened item | 80% | ``` ## Results [Section titled “Results”](#results) | Strategy | Options | Chunks | Smallest | Largest | | ---------------------------------------- | ------------------------------------- | ------ | -------- | ------- | | [`structure`](../structure/) | `{ size: 200, minSize: 50 }` | 4 | 82 | 128 | | [`heading`](../heading/) | Defaults | 3 | 125 | 212 | | [`paragraph`](../paragraph/) | Defaults | 4 | 82 | 128 | | [`sentence`](../sentence/) | Defaults | 8 | 31 | 83 | | [`sentence-window`](../sentence-window/) | Defaults | 8 | 31 | 83 | | [`parent-child`](../parent-child/) | `{ parentSize: 300, childSize: 100 }` | 10 | 32 | 212 | | [`hierarchical`](../hierarchical/) | `{ levels: [400, 150, 100] }` | 14 | 32 | 212 | | [`recursive`](../recursive/) | `{ size: 200 }` | 4 | 82 | 128 | | [`fixed`](../fixed/) | `{ size: 200 }` | 3 | 66 | 200 | | [`fixed-overlap`](../fixed-overlap/) | `{ size: 200, overlapChars: 50 }` | 3 | 167 | 200 | | [`sliding-window`](../sliding-window/) | `{ size: 200, step: 100 }` | 4 | 173 | 200 | ## Chunk boundaries [Section titled “Chunk boundaries”](#chunk-boundaries) Each line is one chunk: its size in characters, then its first and last lines. Chunks inside a larger chunk are indented. ```txt ## structure: 4 chunks, 82 to 128 chars 125 | # Returns policy … You can return most items within 30 days of delivery. Items must be unused and in their original packaging. 126 | ## Start a return … 3. Print the prepaid shipping label. 128 | ## Refunds … We refund the original payment method within 5 business days of receiving the item. Shipping costs are not refunded. 82 | | Item | Refund | … | Opened item | 80% | ## heading: 3 chunks, 125 to 212 chars 125 | # Returns policy … You can return most items within 30 days of delivery. Items must be unused and in their original packaging. 126 | ## Start a return … 3. Print the prepaid shipping label. 212 | ## Refunds … | Opened item | 80% | ## paragraph: 4 chunks, 82 to 128 chars 125 | # Returns policy … You can return most items within 30 days of delivery. Items must be unused and in their original packaging. 126 | ## Start a return … 3. Print the prepaid shipping label. 128 | ## Refunds … We refund the original payment method within 5 business days of receiving the item. Shipping costs are not refunded. 82 | | Item | Refund | … | Opened item | 80% | ## sentence: 8 chunks, 31 to 83 chars 53 | You can return most items within 30 days of delivery. 53 | Items must be unused and in their original packaging. 31 | 1. Sign in and open **Orders**. 38 | 2. Choose the item you want to return. 36 | 3. Print the prepaid shipping label. 83 | We refund the original payment method within 5 business days of receiving the item. 32 | Shipping costs are not refunded. 82 | | Item | Refund | … | Opened item | 80% | ## sentence-window: 8 chunks, 31 to 83 chars 53 | You can return most items within 30 days of delivery. 53 | Items must be unused and in their original packaging. 31 | 1. Sign in and open **Orders**. 38 | 2. Choose the item you want to return. 36 | 3. Print the prepaid shipping label. 83 | We refund the original payment method within 5 business days of receiving the item. 32 | Shipping costs are not refunded. 82 | | Item | Refund | … | Opened item | 80% | ## parent-child: 10 chunks, 32 to 212 chars 125 | # Returns policy … You can return most items within 30 days of delivery. Items must be unused and in their original packaging. 71 | # Returns policy … You can return most items within 30 days of delivery. 53 | Items must be unused and in their original packaging. 126 | ## Start a return … 3. Print the prepaid shipping label. 89 | ## Start a return … 2. Choose the item you want to return. 36 | 3. Print the prepaid shipping label. 212 | ## Refunds … | Opened item | 80% | 95 | ## Refunds … We refund the original payment method within 5 business days of receiving the item. 32 | Shipping costs are not refunded. 82 | | Item | Refund | … | Opened item | 80% | ## hierarchical: 14 chunks, 32 to 212 chars 125 | # Returns policy … You can return most items within 30 days of delivery. Items must be unused and in their original packaging. 125 | # Returns policy … You can return most items within 30 days of delivery. Items must be unused and in their original packaging. 71 | # Returns policy … You can return most items within 30 days of delivery. 53 | Items must be unused and in their original packaging. 126 | ## Start a return … 3. Print the prepaid shipping label. 126 | ## Start a return … 3. Print the prepaid shipping label. 89 | ## Start a return … 2. Choose the item you want to return. 36 | 3. Print the prepaid shipping label. 212 | ## Refunds … | Opened item | 80% | 128 | ## Refunds … We refund the original payment method within 5 business days of receiving the item. Shipping costs are not refunded. 95 | ## Refunds … We refund the original payment method within 5 business days of receiving the item. 32 | Shipping costs are not refunded. 82 | | Item | Refund | … | Opened item | 80% | 82 | | Item | Refund | … | Opened item | 80% | ## recursive: 4 chunks, 82 to 128 chars 125 | # Returns policy … You can return most items within 30 days of delivery. Items must be unused and in their original packaging. 126 | ## Start a return … 3. Print the prepaid shipping label. 128 | ## Refunds … We refund the original payment method within 5 business days of receiving the item. Shipping costs are not refunded. 82 | | Item | Refund | … | Opened item | 80% | ## fixed: 3 chunks, 66 to 200 chars 200 | # Returns policy … 2. Choose the item you 199 | want to return. … | Item | Refund 66 | | … | Opened item | 80% | ## fixed-overlap: 3 chunks, 167 to 200 chars 200 | # Returns policy … 2. Choose the item you 200 | ign in and open **Orders**. … We refund the original payment method within 5 business days of receiving the item. 167 | thod within 5 business days of receiving the item. Shipping costs are not refunded. … | Opened item | 80% | ## sliding-window: 4 chunks, 173 to 200 chars 200 | # Returns policy … 2. Choose the item you 197 | their original packaging. … We refund the original payment 195 | ou want to return. … | Item | 173 | ent method within 5 business days of receiving the item. Shipping costs are not refunded. … | Opened item | 80% | ``` ## What to look at [Section titled “What to look at”](#what-to-look-at) * **`structure`, `heading`, `paragraph`, and `recursive`** give almost the same chunks here, because each section is small. They differ on longer documents: `heading` never splits a section without `size`, `paragraph` never packs blocks together without `size`, and `recursive` can join small sections. * **`sentence` and `sentence-window`** have the same `text`. The difference is `contextText`, which this page doesn’t show. Neither includes the headings in the text. * **`parent-child` and `hierarchical`** cover the same text once per level, so their chunks add up to more text than the document has. Usually only one level is embedded. * **`fixed`, `fixed-overlap`, and `sliding-window`** cut through the list and the table. `fixed-overlap` and `sliding-window` also start chunks in the middle of words. ## The script [Section titled “The script”](#the-script) The output above comes from this script: ```ts import { type ChunkOptions, chunkDocument } from "docchunk"; const runs: ChunkOptions[] = [ { strategy: "structure", size: 200, minSize: 50 }, { strategy: "heading" }, { strategy: "paragraph" }, { strategy: "sentence" }, { strategy: "sentence-window" }, { strategy: "parent-child", parentSize: 300, childSize: 100 }, { strategy: "hierarchical", levels: [400, 150, 100] }, { strategy: "recursive", size: 200 }, { strategy: "fixed", size: 200 }, { strategy: "fixed-overlap", size: 200, overlapChars: 50 }, { strategy: "sliding-window", size: 200, step: 100 }, ]; for (const options of runs) { const { chunks, stats } = await chunkDocument( { path: "returns-policy.md" }, options, ); const sizes = `${stats.minChars} to ${stats.maxChars} chars`; console.log(`## ${options.strategy}: ${stats.count} chunks, ${sizes}`); for (const chunk of chunks) { const indent = " ".repeat(chunk.level ?? 0); const lines = chunk.text.split("\n"); const preview = lines.length === 1 ? lines[0] : `${lines[0]} … ${lines.at(-1)}`; console.log(`${indent}${chunk.charCount} | ${preview}`); } } ```