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

# Clusters

> Group documents by embedding similarity or by metadata values, label each group with an LLM, and write the groups back onto your documents.

A cluster groups the documents in one or more collections. A **vector** cluster groups by embedding similarity, so documents land together by meaning; use it to discover topics, visual styles or recurring faces. An **attribute** cluster groups by metadata values, like a `GROUP BY`; use it when a field such as `category` already holds the structure. Each run can name its groups with an LLM, and the results become documents you can filter, visualize, or promote into a [taxonomy](https://docs.mixpeek.com/docs/enrich/taxonomies.md).

## Create and run a cluster

A vector cluster needs `collection_ids`, `vector_config.feature_uris` and `vector_config.clustering_method`. `clustering_method` has no default. An attribute cluster needs only `collection_ids` and `attribute_config` ([Attribute clusters](#attribute-clusters)).

```bash cURL theme={null}
curl -X POST "https://api.mixpeek.com/v1/clusters" \
  -H "Authorization: Bearer $MIXPEEK_API_KEY" \
  -H "X-Namespace: $NAMESPACE_ID" \
  -H "Content-Type: application/json" \
  -d '{
    "cluster_name": "product_topics",
    "collection_ids": ["col_products"],
    "vector_config": {
      "feature_uris": ["mixpeek://text_extractor@v1/multilingual_e5_large_instruct_v1"],
      "clustering_method": "hdbscan"
    }
  }'
```

```python Python theme={null}
import os
import requests

resp = requests.post(
    "https://api.mixpeek.com/v1/clusters",
    headers={
        "Authorization": f"Bearer {os.environ['MIXPEEK_API_KEY']}",
        "X-Namespace": os.environ["NAMESPACE_ID"],
    },
    json={
        "cluster_name": "product_topics",
        "collection_ids": [os.environ["COLLECTION_ID"]],
        "vector_config": {
            "feature_uris": ["mixpeek://text_extractor@v1/multilingual_e5_large_instruct_v1"],
            "clustering_method": "hdbscan",
        },
    },
)
print(resp.json()["cluster_id"])
```

```javascript JavaScript theme={null}
const resp = await fetch("https://api.mixpeek.com/v1/clusters", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.MIXPEEK_API_KEY}`,
    "X-Namespace": process.env.NAMESPACE_ID,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    cluster_name: "product_topics",
    collection_ids: [process.env.COLLECTION_ID],
    vector_config: {
      feature_uris: ["mixpeek://text_extractor@v1/multilingual_e5_large_instruct_v1"],
      clustering_method: "hdbscan",
    },
  }),
});
console.log((await resp.json()).cluster_id);
```

* `collection_ids` is a list, even for one collection. Replace `col_products` with your collection ID.
* To name each group with an LLM, add `llm_labeling` ([Label clusters with an LLM](#label-clusters-with-an-llm)).
* Each feature URI has the form `mixpeek://{extractor}@{version}/{model}`, and every collection in `collection_ids` must hold that feature. Copy it from the collection's `vector_indexes`, as shown in [Find the feature URI to search](https://docs.mixpeek.com/docs/extract/collections.md#find-the-feature-uri-to-search).

Creating a cluster runs nothing. Start a run:

```bash cURL theme={null}
curl -X POST "https://api.mixpeek.com/v1/clusters/$CLUSTER_ID/execute" \
  -H "Authorization: Bearer $MIXPEEK_API_KEY" \
  -H "X-Namespace: $NAMESPACE_ID" \
  -H "Content-Type: application/json" \
  -d '{ "mode": "full" }'
```

The call answers at once with a `task_id`. Poll `GET /v1/tasks/{task_id}` until it is `COMPLETED` or `FAILED`. Each run has a `run_id`, listed by `GET /v1/clusters/{cluster_id}/executions`.

## Read the results

| To read | Call |
| - | - |
| Labels, summaries and document counts of the latest run | `GET /v1/clusters/{cluster_id}/groups` |
| Scatter-plot coordinates | `GET /v1/clusters/{cluster_id}/visualization` |
| Every member and centroid of one run, as CSV or Parquet | `GET /v1/clusters/{cluster_id}/executions/{run_id}/export` |
| Which cluster one document is in | `POST /v1/collections/{output_collection_id}/documents/list`, filtered on `source_document_id` |

Assignments are documents in the cluster's output collections. `GET /v1/clusters/{cluster_id}` lists them in `output_collection_ids`. Each output collection holds two kinds of document:

| Document | `is_centroid` | Fields |
| - | - | - |
| Centroid | `true` | One per cluster: `cluster_id`, `cluster_label`, `member_count` |
| Member | `false` | One per clustered document: `cluster_id`, `cluster_label`, `source_document_id` |

A member has its own `document_id`; `source_document_id` is the document you clustered. To find the cluster of document `doc_abc123`:

```bash cURL theme={null}
curl -X POST "https://api.mixpeek.com/v1/collections/$OUTPUT_COLLECTION_ID/documents/list" \
  -H "Authorization: Bearer $MIXPEEK_API_KEY" \
  -H "X-Namespace: $NAMESPACE_ID" \
  -H "Content-Type: application/json" \
  -d '{
    "filters": {
      "AND": [
        { "field": "source_document_id", "operator": "eq", "value": "doc_abc123" },
        { "field": "is_centroid", "operator": "eq", "value": false }
      ]
    }
  }'
```

Filter on `cluster_id` instead to list the members of one cluster. The output collection holds the latest run only; export a run to keep it. With `multi_feature_strategy: "independent"` and several feature URIs, there is one output collection per URI.

### Write groups onto your documents

Set `enrich_source_collection: true` on create to skip the output collection and write the group onto each source document instead, so retrievers can filter and facet on it. Each document gets `cluster_id` and `cluster_label`; `source_enrichment_config.field_mappings` renames them or adds more.

```json Cluster body excerpt theme={null}
{
  "enrich_source_collection": true,
  "source_enrichment_config": {
    "field_mappings": [
      { "source_field": "cluster_id", "target_field": "cluster_id" },
      { "source_field": "cluster_label", "target_field": "cluster_label" },
      { "source_field": "keywords", "target_field": "cluster_keywords" }
    ]
  }
}
```

Available source fields: `cluster_id`, `cluster_label`, `distance_to_centroid`, `member_count`, `keywords`, the visualization coordinates `x`, `y`, `z`, and `metadata.*`. `output_collection_ids` then lists your source collections.

To turn the groups into reusable labels for new documents, promote a run into a taxonomy with `POST /v1/taxonomies/from-documents` ([Build a taxonomy from clusters](https://docs.mixpeek.com/docs/enrich/taxonomies.md#build-a-taxonomy-from-clusters)).

## Choose an algorithm

`clustering_method` takes one of these values. Set its parameters in `vector_config.algorithm_params`.

| `clustering_method` | Use when | Key parameters |
| - | - | - |
| `hdbscan` | You do not know how many clusters to expect. Handles uneven density and marks noise. | `min_cluster_size` (default `5`), `min_samples` |
| `kmeans` | You know the count. Fast. | `n_clusters` (default `8`), `max_iter` |
| `dbscan` | You want density grouping with a fixed distance. | `eps`, `min_samples` |
| `agglomerative` | You want hierarchical merging with a set linkage. | `n_clusters`, `linkage` (`ward`, `complete`, `average`, `single`) |
| `spectral` | Clusters have non-convex shapes. | `n_clusters_spectral` |
| `gaussian_mixture` | You need soft, probabilistic assignment. | `n_components_gmm` |
| `mean_shift` | You want the count found from a bandwidth. | Bandwidth parameters |
| `optics` | Like DBSCAN, with varying density. | `eps`, `min_samples` |

The enum also accepts `leiden`, `evoc`, `attribute_based` and `auto`; see [Create cluster](https://docs.mixpeek.com/docs/api-reference/clusters/create-cluster.md). Start with `hdbscan` when you do not know the count, and `kmeans` when you do.

A run needs at least 2 documents, at least `n_clusters` for K-Means and at least `min_cluster_size` for HDBSCAN. Below that, the run fails with `Insufficient documents for clustering`.

### Attribute clusters

```json Attribute cluster body theme={null}
{
  "cluster_name": "product_categories",
  "collection_ids": ["col_products"],
  "cluster_type": "attribute",
  "attribute_config": { "attributes": ["category", "brand"], "hierarchical_grouping": true }
}
```

With `hierarchical_grouping: true`, groups nest: `Electronics` contains `Apple` and `Samsung`. Without it, groups are flat: `Electronics_Apple`, `Electronics_Samsung`.

## Options

> [accordion] Preprocessing for high-dimensional embeddings
>
> Density-based algorithms over-fragment on embeddings with 1,000 or more dimensions. `preprocessing_steps` runs an ordered list first. Whitening followed by UMAP typically improves HDBSCAN cluster purity by 15 to 30% on those embeddings.
>
> ```json preprocessing_steps theme={null}
> {
>   "preprocessing_steps": [
>     { "method": "whitening", "regularization": 1e-5 },
>     { "method": "umap", "n_components": 50, "n_neighbors": 30, "min_dist": 0.0, "metric": "cosine" }
>   ]
> }
> ```

> [accordion] Several embeddings at once
>
> With more than one feature URI, `multi_feature_strategy` decides how they combine.
>
> | Strategy | Behavior |
> | - | - |
> | `concatenate` (default) | Joins the vectors into one and clusters once. Accepts `feature_weights`. |
> | `independent` | Clusters each feature separately, one output collection each. |
> | `weighted` | Learns the feature weights with Bayesian optimization. |

> [accordion] Centroids
>
> `effective_feature_method` sets how a centroid is computed: `mean` (default), `median` (less sensitive to outliers) or `medoid` (the member closest to the center, so the centroid is a real document).

> [accordion] Sub-clusters
>
> Set `hierarchical: true` and `max_hierarchy_depth` (default `3`) to split broad clusters. A cluster with at least twice `min_cluster_size` members is split again with UMAP and HDBSCAN. Sub-cluster IDs look like `cl_0_sub_1_sub_0`.
>
> | Document | Field | Value |
> | - | - | - |
> | Centroid | `parent_cluster_id` | The cluster one level up; absent at the top |
> | Centroid | `hierarchy_level` | `0` at the top, `1` and deeper below |
> | Centroid | `child_cluster_ids` | The sub-clusters one level down |
> | Member | `cluster_id` | The deepest cluster the document is in |
> | Member | `cluster_path` | Every cluster from the top down to `cluster_id` |
>
> Filter on `cluster_path` to read every member under a top-level cluster. The [agent search stage](https://docs.mixpeek.com/docs/retrieve/stages.md#agent-search) walks this tree.

> [accordion] Third dimension in the Studio scatter plot
>
> `vis_n_components` is `2` (default) or `3`. With `3`, the `z` coordinate is filled and Studio draws it as dot size, from 10 to 50 px.

> [accordion] Prototype on a sample
>
> `sample_size` on the cluster or on one execute call clusters a subset, so you can tune parameters before a full run.

## Label clusters with an LLM

`llm_labeling` sends representative documents from each cluster to a model and stores a label, a summary and keywords on each centroid. `labeling_inputs.input_mappings` picks which fields the model sees; without it the whole document payload is sent as JSON.

```json llm_labeling with text and an image theme={null}
{
  "llm_labeling": {
    "enabled": true,
    "provider": "google",
    "model_name": "gemini-2.5-flash",
    "labeling_inputs": {
      "input_mappings": [
        { "input_key": "text", "source_type": "payload", "path": "headline" },
        { "input_key": "image_url", "source_type": "blob", "path": "document_blobs.0.url" }
      ]
    }
  }
}
```

| Mapping field | Values |
| - | - |
| `input_key` | `text`, `image_url`, `video_url`, `audio_url` |
| `source_type` | `payload` (document field), `blob` (stored asset), `literal` (static value) |
| `path` | Dot path, for `payload` and `blob` |
| `override` | The static value, for `literal` |

Send images or video only to a vision-capable model.

| Setting | Default | Effect |
| - | - | - |
| `max_samples_per_cluster` | Automatic, 3 to 20 | Documents sent per cluster |
| `sample_text_max_length` | `200` | Characters kept from each text input |
| `include_summary`, `include_keywords` | `true` | Generate a summary and keywords |
| `use_embedding_dedup` | `true` | Merge near-identical labels across clusters |
| `embedding_similarity_threshold` | `0.8` | Similarity at which labels merge |
| `cache_ttl_seconds` | `604800` (7 days) | Label cache; `0` disables it |
| `custom_prompt`, `response_shape` | None | Your own instructions and output fields |

### Label from a fixed list

`candidate_labels` makes every cluster take a label from your list: an array of labels, or a map of label to a one-line description, up to 255. This keeps labels stable across runs and across levels of a hierarchical run. With `provider: "typesafe"` and `model_name: "jev-latest"`, Jev picks the label and returns a calibrated probability; it reads text only, writes no summary or keywords, and needs `candidate_labels` or a closed-set `response_shape`. Any other model answers the same question with its own confidence estimate.

```json candidate_labels theme={null}
{
  "llm_labeling": {
    "enabled": true,
    "provider": "typesafe",
    "model_name": "jev-latest",
    "candidate_labels": {
      "Pharmaceutical Ads": "Prescription or OTC drug commercials",
      "Car Ads": "Vehicle sales and lease offers"
    },
    "labeling_inputs": {
      "input_mappings": [{ "input_key": "text", "source_type": "payload", "path": "content" }]
    }
  }
}
```

Each centroid then stores `label_confidence`, `label_candidates` (the top three with probabilities), `label_model` and `label_calibrated` (`true` for Jev).

## Keep clusters current

`mode` on the execute call sets what a run does.

| `mode` | What it does | Use it |
| - | - | - |
| `full` (default) | Clusters every document from scratch | First run, and periodically |
| `assign` | Assigns new documents to existing centroids; documents under `assignment_threshold` (default `0.5` cosine) get `cluster_id = -1` | Between full runs, as documents stream in |
| `composite` | Clusters the centroids of earlier runs listed in `source_execution_ids` | Comparing groupings, such as visual style against messaging theme |

A composite run is fast: a run of 10,000 documents in 50 clusters contributes 50 vectors.

To run without calling execute yourself:

* **Triggers:** `POST /v1/clusters/triggers` with `trigger_type` `cron`, `interval`, `event` or `conditional` and a `schedule_config`. See [Create cluster trigger](https://docs.mixpeek.com/docs/api-reference/cluster-triggers/create-cluster-trigger.md).
* **After each batch:** set `auto_execute_on_batch: true` on the cluster. `auto_execute_min_documents` and `auto_execute_cooldown_seconds` (default `3600`) bound how often it runs.

## Check quality

Every run returns metrics. Check `silhouette_score` and `noise_ratio` after each run.

| Metric | Range | Meaning |
| - | - | - |
| `silhouette_score` | -1 to 1 | Separation between clusters; above 0.5 is good |
| `mean_cosine_to_centroid` | 0 to 1 | How tightly members fit their clusters |
| `noise_ratio` | 0 to 1 | Share marked as noise; high values mean parameters are too strict |
| `cluster_size_entropy` | 0 to 1 | Balance of cluster sizes; 1.0 is perfectly even |
| `should_recluster` | 0 or 1 | Set when the metrics cross their thresholds |

Each member also stores `cosine_similarity_to_centroid`, and each centroid stores `mean_cosine_similarity` and `min_cosine_similarity`.

## Clusters, taxonomies or alerts

| You want to | Use |
| - | - |
| Discover what categories exist | Clusters |
| Apply known categories to new documents | [Taxonomies](https://docs.mixpeek.com/docs/enrich/taxonomies.md) |
| Turn discovered groups into reusable labels | Clusters, then promote to a taxonomy |
| Be notified when something specific appears | [Alerts](https://docs.mixpeek.com/docs/enrich/alerts-and-triggers.md) |

## Related

* [Taxonomies](https://docs.mixpeek.com/docs/enrich/taxonomies.md): label new documents with the groups you found
* [Retriever stages](https://docs.mixpeek.com/docs/retrieve/stages.md#cluster): cluster results at query time
* [Studio](https://docs.mixpeek.com/docs/tools/studio.md): the cluster scatter plot
* [Create cluster](https://docs.mixpeek.com/docs/api-reference/clusters/create-cluster.md) and [Execute clustering](https://docs.mixpeek.com/docs/api-reference/clusters/execute-clustering.md) in the API reference


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