> ## Documentation Index
> Fetch the complete documentation index at: https://docs.cognee.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Custom Chunker

> Register your own chunker, make it the default with DEFAULT_CHUNKER, and keep update() chunk-level

A minimal guide to cutting documents with your own chunker. Use it when the built-in `TextChunker` splits your documents in the wrong places — for example across Markdown sections — and you still want `update()` to re-extract only the chunks an edit touched.

## Before You Start

* Complete [Quickstart](https://docs.cognee.ai/getting-started/quickstart.md) to understand basic operations
* Ensure you have [LLM Providers](https://docs.cognee.ai/setup-configuration/llm-providers.md) configured (`LLM_API_KEY` in `.env`)
* Read [Chunkers](https://docs.cognee.ai/core-concepts/further-concepts/chunkers.md) for the rules a custom chunker follows
* No data is required up front — the script ingests its own text, but it starts with `cognee.forget(everything=True)`, which wipes all existing Cognee data; run it against a setup you can afford to reset

## Code in Action

```python theme={null}
import asyncio
import os
import re

# A deployment sets this in its environment or .env.
os.environ.setdefault("DEFAULT_CHUNKER", "SectionChunker")

import cognee
from cognee.modules.chunking.chunk_id import content_chunk_id
from cognee.modules.chunking.chunker_registry import register_chunker
from cognee.modules.chunking.TextChunker import TextChunker

DATASET = "custom_chunker_guide"

HANDBOOK = """# Opening hours

The Quillon office opens at nine and closes at six on weekdays.

# Visitors

Visitors sign in at the front desk and are met by Ingrid Solvay.

# Deliveries

Deliveries are taken at the side entrance by Tomas Ferreira until noon.
"""


class SectionChunker(TextChunker):
    """One Markdown section per chunk; TextChunker cuts a section over the budget."""

    chunker_id = "section_chunker_v1"

    async def read(self):
        document_id = str(self.document.id)
        occurrences: dict[str, int] = {}
        async for text in self.get_text():
            # Split before each heading line. The pieces join back to ``text``.
            for section in re.split(r"(?m)^(?=#)", text):
                if not section:
                    continue

                async def section_text(section=section):
                    yield section

                section_chunker = TextChunker(self.document, section_text, self.max_chunk_size)
                async for chunk in section_chunker.read():
                    # Chunk ids count repeated texts over the document, not one section.
                    occurrence = occurrences.get(chunk.content_hash, 0)
                    occurrences[chunk.content_hash] = occurrence + 1
                    chunk.id = content_chunk_id(document_id, chunk.content_hash, occurrence)
                    chunk.chunker_id = self.chunker_id
                    chunk.chunk_index = self.chunk_index
                    self.chunk_index += 1
                    yield chunk


async def main():
    # Register before the first cognify call; DEFAULT_CHUNKER names it.
    register_chunker("SectionChunker", SectionChunker)

    # Start clean (optional in your app)
    await cognee.forget(everything=True)

    await cognee.remember(HANDBOOK, dataset_name=DATASET, self_improvement=False)

    dataset = next(d for d in await cognee.datasets.list_datasets() if d.name == DATASET)
    document = (await cognee.datasets.list_data(dataset.id))[0]

    # Edit one section. Only its chunk is cut and extracted again.
    edited = HANDBOOK.replace("closes at six", "closes at eight")
    result = await cognee.update(data_id=document.id, data=edited, dataset_id=dataset.id)
    print(
        f"update: {result['status']}, regions={result['regions']}, "
        f"kept={result['kept_chunks']}, added={result['added_chunks']}, "
        f"deleted={result['deleted_chunks']}"
    )

    answers = await cognee.recall("When does the Quillon office close?", datasets=[DATASET])
    print(answers[0].text if answers else "(nothing found)")


if __name__ == "__main__":
    asyncio.run(main())
```

## What Just Happened

### Step 1: Select the Chunker by Name

```python theme={null}
# A deployment sets this in its environment or .env.
os.environ.setdefault("DEFAULT_CHUNKER", "SectionChunker")
```

Every call that passes no `chunker` uses the one `DEFAULT_CHUNKER` names. See [Default chunker for a deployment](https://docs.cognee.ai/core-concepts/further-concepts/chunkers.md#default-chunker-for-a-deployment) for how the setting resolves.

### Step 2: Define the Chunker

```python theme={null}
class SectionChunker(TextChunker):
    """One Markdown section per chunk; TextChunker cuts a section over the budget."""

    chunker_id = "section_chunker_v1"

    async def read(self):
        document_id = str(self.document.id)
        occurrences: dict[str, int] = {}
        async for text in self.get_text():
            # Split before each heading line. The pieces join back to ``text``.
            for section in re.split(r"(?m)^(?=#)", text):
                if not section:
                    continue

                async def section_text(section=section):
                    yield section

                section_chunker = TextChunker(self.document, section_text, self.max_chunk_size)
                async for chunk in section_chunker.read():
                    # Chunk ids count repeated texts over the document, not one section.
                    occurrence = occurrences.get(chunk.content_hash, 0)
                    occurrences[chunk.content_hash] = occurrence + 1
                    chunk.id = content_chunk_id(document_id, chunk.content_hash, occurrence)
                    chunk.chunker_id = self.chunker_id
                    chunk.chunk_index = self.chunk_index
                    self.chunk_index += 1
                    yield chunk
```

`read()` splits the text before each heading line, then hands each section to an inner `TextChunker`, so a section over the token budget is still cut to size. The split uses a lookahead, so the sections join back to the original text with nothing lost or repeated. That is what lets `update()` [replace only the chunks an edit touched](https://docs.cognee.ai/core-concepts/further-concepts/chunkers.md#custom-chunkers).

The inner `TextChunker` sees one section at a time, so the ids it gives its chunks only count repeated text within that section. Two sections with identical text would then get the same chunk id. The loop therefore rebuilds each id with `content_chunk_id()`, counting repeats across the whole document. It also stamps the outer chunker's `chunker_id` and renumbers `chunk_index` so the indexes run through the whole document.

### Step 3: Register the Chunker

```python theme={null}
    # Register before the first cognify call; DEFAULT_CHUNKER names it.
    register_chunker("SectionChunker", SectionChunker)
```

This makes `"SectionChunker"` a valid value for `DEFAULT_CHUNKER`. A server needs the same call at startup.

### Step 4: Update One Section

```python theme={null}
    # Edit one section. Only its chunk is cut and extracted again.
    edited = HANDBOOK.replace("closes at six", "closes at eight")
    result = await cognee.update(data_id=document.id, data=edited, dataset_id=dataset.id)
```

The edit changes only the "Opening hours" section. `update()` reports `incremental` with one region: it re-cuts that section, extracts its new chunk, and keeps the chunks of the other two sections as they are. `recall()` then answers with the new closing time. To see a full rebuild instead, change `DEFAULT_CHUNKER` between `remember()` and `update()`; the [`update()` reference](https://docs.cognee.ai/python-api/update#returns) lists the fallback reasons.

> [card] [Chunkers](https://docs.cognee.ai/core-concepts/further-concepts/chunkers.md)
>
> How Cognee splits documents into chunks.

> [card] [update()](https://docs.cognee.ai/python-api/update.md)
>
> Parameters and return values of update().


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.