1.  [](/)
2.  [Code examples](/recipes)
3.  Document Classification Pipeline

Back to code examples

# Document Classification Pipeline

Classify documents into custom business categories using layout-aware extraction and taxonomy enrichment. Handles invoices, contracts, reports, forms, and correspondence by analyzing both textual content and visual document structure.

text

image

Multi-Stage

[Run in Builder](/build?recipe=document-classification)

Python

cURL

import requests

from mixpeek import Mixpeek

client \= Mixpeek(api\_key\="YOUR\_API\_KEY", namespace\="documents")

API \= "https://api.mixpeek.com/v1"

HEADERS \= {"Authorization": "Bearer YOUR\_API\_KEY", "X-Namespace": "documents"}

\# 1. Exemplars: sample invoices, contracts, reports, forms and letters

example\_bucket \= client.buckets.create(

    bucket\_name\="document-examples",

    bucket\_schema\={"properties": {"document": {"type": "pdf"}}},

)

examples \= client.collections.create(

    collection\_name\="document-examples",

    source\={"type": "bucket", "bucket\_ids": \[example\_bucket\["bucket\_id"\]\]},

    feature\_extractor\={

        "feature\_extractor\_name": "document\_graph\_extractor",

        "version": "v1",

    },

)

client.buckets.upload(

    example\_bucket\["bucket\_id"\],

    blobs\=\[{"property": "document", "type": "pdf", "data": "s3://your-bucket/examples/invoice-01.pdf"}\],

)

client.collections.trigger(examples\["collection\_id"\])

\# 2. The retriever the taxonomy uses to find the closest exemplar block

matcher \= client.retrievers.create(

    retriever\_name\="document-type-matcher",

    collection\_identifiers\=\["document-examples"\],

    input\_schema\={"query": {"type": "text", "required": True}},

    stages\=\[

        {

            "stage\_name": "search",

            "stage\_id": "feature\_search",

            "parameters": {

                "searches": \[

                    {

                        "feature\_uri": "mixpeek://document\_graph\_extractor@v1/intfloat\_\_multilingual\_e5\_large\_instruct",

                        "query": {"input\_mode": "text", "value": "{{INPUT.query}}"},

                        "top\_k": 3,

                    },

                \],

                "final\_top\_k": 3,

            },

        },

    \],

)

\# A flat taxonomy matches each document, through a retriever, against a

\# collection of labeled examples. The SDK has no taxonomies resource, so this is REST.

taxonomy \= requests.post(API + "/taxonomies", headers\=HEADERS, json\={

    "taxonomy\_name": "document\_types",

    "config": {

        "taxonomy\_type": "flat",

        "retriever\_id": matcher\["retriever\_id"\],

        "input\_mappings": \[{"input\_key": "query", "source\_type": "payload", "path": "text\_raw"}\],

        "source\_collection": {"collection\_id": examples\["collection\_id"\]},

    },

}).json()

\# 3. Incoming documents are labeled as they are written

bucket \= client.buckets.create(

    bucket\_name\="incoming",

    bucket\_schema\={"properties": {"document": {"type": "pdf"}}},

)

incoming \= client.collections.create(

    collection\_name\="incoming-documents",

    source\={"type": "bucket", "bucket\_ids": \[bucket\["bucket\_id"\]\]},

    feature\_extractor\={

        "feature\_extractor\_name": "document\_graph\_extractor",

        "version": "v1",

    },

    taxonomy\_applications\=\[{"taxonomy\_id": taxonomy\["taxonomy\_id"\], "execution\_mode": "materialize"}\],

)

client.buckets.upload(

    bucket\["bucket\_id"\],

    blobs\=\[{"property": "document", "type": "pdf", "data": "s3://your-bucket/incoming/scan-2291.pdf"}\],

)

client.collections.trigger(incoming\["collection\_id"\])

\# 4. An LLM check for blocks whose label needs a second look

review \= client.retrievers.create(

    retriever\_name\="classification-review",

    collection\_identifiers\=\["incoming-documents"\],

    input\_schema\={"query": {"type": "text", "required": True}},

    stages\=\[

        {

            "stage\_name": "search",

            "stage\_id": "feature\_search",

            "parameters": {

                "searches": \[

                    {

                        "feature\_uri": "mixpeek://document\_graph\_extractor@v1/intfloat\_\_multilingual\_e5\_large\_instruct",

                        "query": {"input\_mode": "text", "value": "{{INPUT.query}}"},

                        "top\_k": 50,

                    },

                \],

                "final\_top\_k": 50,

            },

        },

        {"stage\_name": "validate", "stage\_id": "llm\_filter", "parameters": {"criteria": "Keep blocks that read like an invoice: line items, totals and a due date.", "provider": "google", "model\_name": "gemini-2.5-flash-lite"}},

    \],

)

results \= client.retrievers.execute(review\["retriever\_id"\], inputs\={"query": "amount due and payment terms"})

print(len(results\["documents"\]), "invoice-like blocks")

### Feature Extractors

Document Graph Extractor

Decompose PDFs into spatial blocks (paragraphs, tables, forms, headers) with layout classification and E5 text embeddings.

### Retriever Stages

feature search

Search and filter documents by vector similarity using feature embeddings

filter

taxonomy enrich

Classify documents against taxonomy nodes via vector similarity

apply

llm filter

Filter documents using LLM-based semantic evaluation

filter

## Frequently asked questions

### How many example documents do I need per category?

Typically 5-20 representative examples per category provide strong classification accuracy. The taxonomy uses these as embedding centroids, so quality matters more than quantity.

### Can the classifier handle multi-page documents?

Yes. Each page is individually classified, then page-level labels are aggregated to produce a document-level classification with confidence scores.

### What happens when a document does not match any category?

Documents that fall below the confidence threshold for all categories are labeled as "unclassified." You can set the threshold and route these for human review.

## Use Cases Using This Recipe

Advanced

12 min

### Clinical NLP at Scale

Extract structured intelligence from clinical notes, pathology reports, and medical records

94% F1 on medical NER benchmarks

Entity extraction accuracy

[

healthcare

](/solutions/healthcare)

Who It's For

Healthcare IT teams, clinical informatics departments, and health systems processing thousands of clinical documents daily

[View Details](/use-cases/clinical-nlp)

## Related code examples and resources

Pages on the same stages, extractors and patterns.

[

Extractor

### Document Graph Extractor

Decompose PDFs into spatial blocks (paragraphs, tables, forms, headers) with layout classification and E5 text embeddings.

Learn more





](/extractors/document-graph)[

Recipe

### Multimodal Content Moderation

Automated content moderation pipeline that analyzes text, images, and video for policy violations. Uses hierarchical taxonomy classification to label content as safe, sensitive, or prohibited across multiple categories simultaneously.

Learn more





](/recipes/multimodal-content-moderation)[

Recipe

### Document Intelligence Search

Extract and search through PDFs, presentations, and documents. Combines OCR, layout analysis, and semantic search for comprehensive document retrieval.

Learn more





](/recipes/document-search-pipeline)[

Recipe

### PDF Data Extraction Pipeline

Extract structured data from PDFs including tables, forms, and text. Convert unstructured documents into structured, queryable data.

Learn more





](/recipes/pdf-extraction-pipeline)[

Recipe

### Document RAG Pipeline

Retrieval-augmented generation for document collections. Extracts text, tables, and figures from PDFs using OCR and layout analysis, then retrieves relevant page sections to answer natural language questions with precise page and section citations.

Learn more





](/recipes/document-rag-pipeline)[

Recipe

### BYO Embeddings Vector Search

Bring pre-computed embeddings from any provider (OpenAI, Cohere, Together, etc.) and upsert them directly into MVS for instant vector search. No feature extractors, no pipelines -- just embeddings in, results out.

Learn more





](/recipes/mvs-byo-embeddings-search)