> ## 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.

# Hierarchical search over clusters

> Group a text collection into clusters labeled from your own vocabulary, then answer a query by walking that tree.

Group a text collection into clusters labeled from your own vocabulary, then answer a query by walking that tree. Jev picks the most likely branch at each level and the retriever returns members of the best cluster, with the path it took.

> [card] [Jump to the manifest](#the-manifest)
>
> `hierarchical-cluster-search.namespace.yaml`: apply it with one API call, then read the walkthrough below to change it.

## At a glance

| | |
| - | - |
| **Creates** | 1 namespace, 1 bucket, 1 collection, 2 retrievers, 1 cluster |
| **Extractors** | [`text_extractor`](https://docs.mixpeek.com/docs/extract/extractors#text) v1 |
| **Daily spend budget** | 1 USD, set on the namespace. Queries are not capped. |
| **Sample data** | 12 objects, uploaded to `content` when you apply |

## How the pieces connect

Buckets hold what you upload, collections turn it into searchable documents, and retrievers answer queries over the collections.

```mermaid theme={null}
flowchart LR
  b0[("content")]
  c1["content-text<br/>text_extractor v1"]
  r2{{"content-search"}}
  r3{{"browse-content-tree"}}
  b0 --> c1
  c1 --> r2
```

## Deploy it

**1. Get the manifest**

```bash theme={null}
# Copy the manifest from the bottom of this page into hierarchical-cluster-search.namespace.yaml
```

**2. Validate it**

Validate runs every check apply runs and creates nothing. Fix each entry in `errors`, then run it again.

```bash theme={null}
curl -X POST https://api.mixpeek.com/v1/manifest/validate \
  -H "Authorization: Bearer $MIXPEEK_API_KEY" \
  -F "manifest_file=@hierarchical-cluster-search.namespace.yaml"
```

**3. Apply it**

Apply creates every resource in one call. `wait_for_seed=true` also waits until the sample objects are processed, so the first query below has documents to return.

```bash theme={null}
curl -X POST "https://api.mixpeek.com/v1/manifest/apply?wait_for_seed=true" \
  -H "Authorization: Bearer $MIXPEEK_API_KEY" \
  -F "manifest_file=@hierarchical-cluster-search.namespace.yaml"
```

The response lists each resource with its outcome in `resources`. Apply refuses a resource that already exists and rolls the whole apply back, so to apply the file again over this namespace add `?mode=create_missing`, which creates only what is missing.

## Run the first query

Look up the namespace id by name, then run `content-search`. Check `status` and `warnings` along with `documents`: a run that times out still answers 200, with `status` `degraded`.

```bash cURL theme={null}
NAMESPACE_ID=$(curl -s https://api.mixpeek.com/v1/namespaces/hierarchical-cluster-search \
  -H "Authorization: Bearer $MIXPEEK_API_KEY" | jq -r .namespace_id)

curl -X POST https://api.mixpeek.com/v1/retrievers/content-search/execute \
  -H "Authorization: Bearer $MIXPEEK_API_KEY" \
  -H "X-Namespace: $NAMESPACE_ID" \
  -H "Content-Type: application/json" \
  -d '{"inputs": {"query": "drug commercials that disclose side effects"}}' \
  | jq '{status, warnings, documents: [.documents[] | {document_id, score}]}'
```

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

AUTH = {"Authorization": f"Bearer {os.environ['MIXPEEK_API_KEY']}"}
ns = requests.get("https://api.mixpeek.com/v1/namespaces/hierarchical-cluster-search", headers=AUTH).json()

run = requests.post(
    "https://api.mixpeek.com/v1/retrievers/content-search/execute",
    headers={**AUTH, "X-Namespace": ns["namespace_id"]},
    json={"inputs": {"query": "drug commercials that disclose side effects"}},
).json()

print(run["status"], run["warnings"])  # "completed" on a clean run
for doc in run["documents"]:
    print(doc["document_id"], doc["score"])
```

```javascript JavaScript theme={null}
const auth = { Authorization: `Bearer ${process.env.MIXPEEK_API_KEY}` };
const ns = await fetch("https://api.mixpeek.com/v1/namespaces/hierarchical-cluster-search", { headers: auth }).then((r) => r.json());

const run = await fetch("https://api.mixpeek.com/v1/retrievers/content-search/execute", {
  method: "POST",
  headers: { ...auth, "X-Namespace": ns.namespace_id, "Content-Type": "application/json" },
  body: JSON.stringify({"inputs": {"query": "drug commercials that disclose side effects"}}),
}).then((r) => r.json());

console.log(run.status, run.warnings); // "completed" on a clean run
for (const doc of run.documents) console.log(doc.document_id, doc.score);
```

## Add your own data

Each object you add to a bucket is processed by every collection that reads it. This adds one object to `content`. `NAMESPACE_ID` is the id from the namespace lookup above.

```bash cURL theme={null}
curl -X POST "https://api.mixpeek.com/v1/buckets/content/objects?auto_process=true" \
  -H "Authorization: Bearer $MIXPEEK_API_KEY" \
  -H "X-Namespace: $NAMESPACE_ID" \
  -H "Content-Type: application/json" \
  -d '{"headline": "example", "blobs": [{"property": "content", "type": "text", "data": "The text you want indexed."}]}'
```

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

HEADERS = {"Authorization": f"Bearer {os.environ['MIXPEEK_API_KEY']}", "X-Namespace": os.environ["NAMESPACE_ID"]}

obj = requests.post(
    "https://api.mixpeek.com/v1/buckets/content/objects",
    params={"auto_process": "true"},
    headers=HEADERS,
    json={
        "headline": "example",
        "blobs": [
            {
                "property": "content",
                "type": "text",
                "data": "The text you want indexed."
            }
        ]
    },
).json()
print(obj["object_id"], obj["status"])  # PENDING until processing finishes
```

```javascript JavaScript theme={null}
const headers = {
  Authorization: `Bearer ${process.env.MIXPEEK_API_KEY}`,
  "X-Namespace": process.env.NAMESPACE_ID,
  "Content-Type": "application/json",
};

const obj = await fetch("https://api.mixpeek.com/v1/buckets/content/objects?auto_process=true", {
  method: "POST",
  headers,
  body: JSON.stringify({
    "headline": "example",
    "blobs": [
      {
        "property": "content",
        "type": "text",
        "data": "The text you want indexed."
      }
    ]
  }),
}).then((r) => r.json());
console.log(obj.object_id, obj.status); // PENDING until processing finishes
```

The object is `PENDING` until processing finishes, then `COMPLETED` or `FAILED`. [Buckets and objects](https://docs.mixpeek.com/docs/ingest/buckets.md) covers object states, retries and duplicates.

## Retrievers

### `content-search`

Plain vector search over content-text. Answers as soon as the seed is indexed.

**Stages:** [`feature_search`](https://docs.mixpeek.com/docs/retrieve/stages#feature-search)

**Searches:** `content-text`

| Input | Type | Required | Description |
| - | - | - | - |
| `query` | text | yes | What to look for, in plain words |

### `browse-content-tree`

Walks the content-tree clusters top-down with Jev and returns members of the best leaf cluster. Answers after the cluster has run once.

**Stages:** [`agent_search`](https://docs.mixpeek.com/docs/retrieve/stages#agent-search)

**Searches:** `content-tree`

| Input | Type | Required | Description |
| - | - | - | - |
| `query` | text | yes | What to look for; Jev picks the cluster most likely to hold it at each level |

## Collections

Each collection runs one extractor over a bucket, or over another collection's documents.

> [accordion] content-text
>
> text\_extractor\@v1 over bucket content. Feeds content-search and the content-tree cluster.
>
> **Reads** bucket `content` with [`text_extractor`](https://docs.mixpeek.com/docs/extract/extractors#text) v1.
>
> **Inputs:** `text` ← `content`
>
> **Copied onto each document:** `headline`

## Also created

**[Clusters](https://docs.mixpeek.com/docs/enrich/clusters.md)**

* `content-tree`: Groups content-text by meaning and labels every cluster from a fixed vocabulary, so a retriever can walk the groups top-down.

## The manifest

Every resource above comes from this file. Change it and apply it again with `?mode=upsert` to update what exists. [Manifests](https://docs.mixpeek.com/docs/manage/manifests.md) documents each field.

```yaml hierarchical-cluster-search.namespace.yaml expandable theme={null}
# hierarchical-cluster-search: one manifest spins up the namespace.
# Text documents are embedded, grouped into clusters that Jev labels from a fixed
# vocabulary, and searched two ways: plain vector search over the documents, and a
# retriever that walks the labeled cluster tree top-down before returning members.
# Validate with POST /v1/manifest/validate, apply with POST /v1/manifest/apply.
# Applying a SECOND time, over a namespace this template already created: use
# POST /v1/manifest/apply?mode=create_missing, which creates what is missing and leaves
# what exists alone. Use mode=upsert to also patch resources that have drifted from this file.
#
# The cluster is created by apply but not run. Run it once the seed is indexed:
#   POST /v1/clusters/<cluster_id>/execute
# browse-content-tree reads the cluster's output collection, which is empty until then.
version: '1.0'
metadata:
  name: hierarchical-cluster-search
  description: "Clusters a text collection into a labeled hierarchy and answers queries by walking it with Jev."
namespaces:
  - name: hierarchical-cluster-search
    description: "Everything below lives in this namespace."
    feature_extractors:
      - name: text_extractor
        version: v1
    # Daily spend budget, in dollars of what you are charged (1,000 credits a dollar).
    # New batches pause once the namespace has spent this much today; queries are not capped.
    # Raise it later on the namespace: PATCH /v1/namespaces/<id> {"spend_budget": {"daily_usd": N}}.
    budget:
      daily_usd: 1

buckets:
  - name: content
    namespace: hierarchical-cluster-search
    description: "Short text items to organize: ad scripts, video descriptions, articles. Upload through the API or Studio."
    schema:
      properties:
        content:
          type: text
          required: true
        headline:
          type: string

collections:
  - name: content-text
    namespace: hierarchical-cluster-search
    description: "text_extractor@v1 over bucket content. Feeds content-search and the content-tree cluster."
    source:
      type: bucket
      bucket: content
    feature_extractor:
      name: text_extractor
      version: v1
      input_mappings:
        text: content
      field_passthrough:
        - source_path: headline
    enabled: true

clusters:
  - name: content-tree
    namespace: hierarchical-cluster-search
    description: "Groups content-text by meaning and labels every cluster from a fixed vocabulary, so a retriever can walk the groups top-down."
    source_collections:
      - content-text
    cluster_type: vector
    vector_config:
      feature_uris:
        - mixpeek://text_extractor@v1/multilingual_e5_large_instruct_v1
      clustering_method: kmeans
      algorithm_params:
        n_clusters: 3
      hierarchical: true
      max_hierarchy_depth: 2
    llm_labeling:
      enabled: true
      provider: typesafe
      model_name: jev-latest
      candidate_labels:
        - Product Ads
        - Sports
        - Cooking
        - Pharmaceutical Ads
        - Car Ads
        - Skateboarding
        - Surfing
        - Baking
        - Grilling
      labeling_inputs:
        input_mappings:
          - {input_key: text, source_type: payload, path: text}

retrievers:
  - name: content-search
    namespace: hierarchical-cluster-search
    description: "Plain vector search over content-text. Answers as soon as the seed is indexed."
    collections:
      - content-text
    input_schema:
      query:
        type: text
        required: true
        description: "What to look for, in plain words"
    stages:
      - stage_name: search
        stage_id: feature_search
        parameters:
          searches:
            - feature_uri: "mixpeek://text_extractor@v1/multilingual_e5_large_instruct_v1"
              query:
                input_mode: text
                value: "{{INPUT.query}}"
              top_k: 10
          final_top_k: 10
    tags:
      - template:hierarchical-cluster-search
  - name: browse-content-tree
    namespace: hierarchical-cluster-search
    description: "Walks the content-tree clusters top-down with Jev and returns members of the best leaf cluster. Answers after the cluster has run once."
    collections:
      # The cluster's output collection. A cluster creates it and names it after itself.
      - content-tree
    input_schema:
      query:
        type: text
        required: true
        description: "What to look for; Jev picks the cluster most likely to hold it at each level"
    stages:
      - stage_name: browse
        stage_id: agent_search
        parameters:
          strategy: cluster_navigation
          model_name: jev-latest
          # Below the executor's 25 s stage ceiling, so the stage's own stop path fires first.
          timeout_seconds: 20
          cluster_navigation:
            beam_width: 2
            max_leaf_clusters: 1
    tags:
      - template:hierarchical-cluster-search

# Twelve short ad scripts written for this template, four per broad theme (sports,
# cooking, advertising), two per sub-theme. Ingested inline by one bounded batch after
# apply, so nothing is fetched.
seed:
  - bucket: content
    max_objects: 12
    objects:
      - texts: {content: "A skater drops into an empty pool at dawn, carves the deep end and pops a frontside air over the coping."}
        headline: "Dawn session at the pool"
      - texts: {content: "Street skating tutorial: how to ollie a three-stair set, where to put your back foot, and how to land bolts."}
        headline: "Ollie the three-stair"
      - texts: {content: "Surfers paddle out through cold winter swell and ride long right-hand point breaks until the light goes."}
        headline: "Winter point break"
      - texts: {content: "Beginner surf lesson on a foam board: reading the waves, timing the pop-up, and staying out of the rip current."}
        headline: "Your first wave"
      - texts: {content: "Sourdough at home: feed the starter, fold the dough every half hour, and bake in a covered pot for a crisp crust."}
        headline: "Weekend sourdough"
      - texts: {content: "Three-layer chocolate cake with buttercream frosting, baked in round tins and cooled before you stack it."}
        headline: "Birthday chocolate cake"
      - texts: {content: "Grill thick ribeye steaks over hot charcoal, rest them five minutes, and slice against the grain."}
        headline: "Charcoal ribeye"
      - texts: {content: "Backyard barbecue: smoke pork ribs low and slow for six hours, then brush on sauce over direct heat."}
        headline: "Low and slow ribs"
      - texts: {content: "Ask your doctor if this allergy tablet is right for you. Side effects may include drowsiness, dry mouth and headache."}
        headline: "Allergy relief commercial"
      - texts: {content: "A once-daily cholesterol medication. Do not take it if you are pregnant. Tell your doctor about muscle pain."}
        headline: "Cholesterol drug commercial"
      - texts: {content: "The new hybrid SUV seats seven, tows two tons and gets forty miles per gallon. Lease it this weekend at your dealer."}
        headline: "Hybrid SUV launch"
      - texts: {content: "A pickup truck climbs a muddy mountain trail with a full load in the bed. Built tough, now with a ten-year warranty."}
        headline: "Pickup truck spot"
acceptance:
  max_cost_usd: 0.25
  steps:
    - name: content-indexed
      kind: documents
      collection: content-text
      expect: {min_documents: 12}
    - name: content-search-answers
      kind: query
      retriever: content-search
      inputs: {query: drug commercials that disclose side effects}
      expect: {min_results: 1}
```

## Hand it to an agent

Paste this prompt into Claude Code, Cursor or another coding agent. To give the agent this whole page instead, use **Copy page** in the menu at the top of the page, or point it at the page's Markdown at `https://mixpeek.com/docs/templates/hierarchical-cluster-search.md`.

```text Prompt theme={null}
Set up the Mixpeek "Hierarchical search over clusters" template in my organization. My API key is in MIXPEEK_API_KEY.
1. Save the manifest at the bottom of https://mixpeek.com/docs/templates/hierarchical-cluster-search as hierarchical-cluster-search.namespace.yaml.
2. POST it to https://api.mixpeek.com/v1/manifest/validate as the multipart field manifest_file, with the header Authorization: Bearer $MIXPEEK_API_KEY. Fix every entry in errors and validate again.
3. POST the same file to https://api.mixpeek.com/v1/manifest/apply?wait_for_seed=true. Every entry in resources should be created.
4. GET https://api.mixpeek.com/v1/namespaces/hierarchical-cluster-search and keep namespace_id. Send it as the X-Namespace header on every call below.
5. POST {"inputs": {"query": "drug commercials that disclose side effects"}} to https://api.mixpeek.com/v1/retrievers/content-search/execute. Read documents, check that status is completed, and print warnings.
Reference for this template: https://mixpeek.com/docs/templates/hierarchical-cluster-search.md
```

## How it works

Hierarchical search first picks the part of the corpus most likely to hold the answer, then returns documents from inside it. This template builds it beside plain vector search over the same data.

1. `content-text` embeds each object's `content` with [`text_extractor`](https://docs.mixpeek.com/docs/extract/extractors#text) into the `multilingual_e5_large_instruct_v1` feature. `content-search` searches that feature directly.
2. The `content-tree` cluster groups those vectors with k-means. [Jev](https://docs.mixpeek.com/docs/extract/extractors.md) then labels every cluster by picking one name from `candidate_labels`, and stores the pick's probability as `label_confidence`.
3. A cluster run writes the `content-tree` output collection: one centroid document per cluster (`is_centroid`, `cluster_id`, `label`, `parent_cluster_id`) plus a copy of every member document with its source's vector.
4. `browse-content-tree` runs an [`agent_search`](https://docs.mixpeek.com/docs/retrieve/stages#agent-search) stage with the `cluster_navigation` strategy over that collection. It builds the tree from `parent_cluster_id` and asks Jev at each level which child cluster most likely answers the query.

Apply creates the cluster but does not run it, so `browse-content-tree` returns no documents until the first run.

## Run the cluster

**1. Start a run**

Look up the cluster id by name, then execute it. The call returns a task.

```bash cURL theme={null}
CLUSTER_ID=$(curl -s https://api.mixpeek.com/v1/clusters/content-tree \
  -H "Authorization: Bearer $MIXPEEK_API_KEY" \
  -H "X-Namespace: $NAMESPACE_ID" | jq -r .cluster_id)

TASK_ID=$(curl -s -X POST "https://api.mixpeek.com/v1/clusters/$CLUSTER_ID/execute" \
  -H "Authorization: Bearer $MIXPEEK_API_KEY" \
  -H "X-Namespace: $NAMESPACE_ID" | jq -r .task_id)
echo "$TASK_ID"
```

**2. Wait for it to finish**

Poll the task until `status` is `COMPLETED`, `COMPLETED_WITH_ERRORS`, `FAILED` or `CANCELED`.

```bash cURL theme={null}
curl -s "https://api.mixpeek.com/v1/tasks/$TASK_ID" \
  -H "Authorization: Bearer $MIXPEEK_API_KEY" \
  -H "X-Namespace: $NAMESPACE_ID" | jq '{status, error}'
```

**3. Walk the tree**

Run `browse-content-tree` with the same query you gave `content-search`.

```bash cURL theme={null}
curl -s -X POST https://api.mixpeek.com/v1/retrievers/browse-content-tree/execute \
  -H "Authorization: Bearer $MIXPEEK_API_KEY" \
  -H "X-Namespace: $NAMESPACE_ID" \
  -H "Content-Type: application/json" \
  -d '{"inputs": {"query": "drug commercials that disclose side effects"}}' \
  | jq '{status, warnings, path: .stage_statistics.stages.browse.metadata.chosen_clusters, documents: [.documents[] | {document_id, headline, cluster_path, cluster_path_score}]}'
```

## Read the path Jev took

The stage records its walk under `stage_statistics.stages.browse.metadata`:

| Field | What it holds |
| - | - |
| `chosen_clusters` | Each kept leaf with its `cluster_id`, `label`, `path` (labels from the top) and `score` |
| `navigation_trace` | The candidates and the probability Jev gave each one, at every level |
| `error` | Present when the stage found no centroids or no `query` input |

Each returned document carries `cluster_path` and `cluster_path_score`. A path's score is the geometric mean of its decision probabilities, so a shallow leaf and a deep leaf compare fairly.

If `error` says no centroid documents were found, the cluster has not completed a run yet.

## Why these settings

* **`n_clusters: 3`** matches the seed: twelve scripts in three themes (sports, cooking, ads).
* **`hierarchical: true` with `max_hierarchy_depth: 2`** asks for sub-clusters under each top-level cluster. A cluster splits only when it holds at least twice `min_cluster_size` members. k-means takes no `min_cluster_size`, so the default of 50 applies, and the twelve seed documents give a one-level tree.
* **`provider: typesafe` and `model_name: jev-latest`** label each cluster by choosing from `candidate_labels`. Jev reads text only, so `labeling_inputs` maps the document's `text` field. Jev needs 2 to 255 labels; sub-clusters are labeled from the same list, so list names for every level.
* **`beam_width: 2`** keeps two paths per level. `1` is greedy descent. A wider beam lets a later level correct an ambiguous early choice.
* **`max_leaf_clusters: 1`** returns members of the best leaf only. Raise it when a query can span topics.
* **`timeout_seconds: 20`** keeps the stage under the executor's 25-second stage ceiling.

## Variations

Each change below edits the manifest. Apply it again with `?mode=upsert`, then run the cluster again.

### Get a second level

HDBSCAN accepts `min_cluster_size`, so it controls when a cluster splits. With `min_cluster_size: 5`, a cluster with 10 or more members splits again. HDBSCAN picks the number of clusters itself and marks outliers as noise, so it suits a few hundred documents or more.

```yaml content-tree vector_config theme={null}
    vector_config:
      feature_uris:
        - mixpeek://text_extractor@v1/multilingual_e5_large_instruct_v1
      clustering_method: hdbscan
      algorithm_params:
        min_cluster_size: 5
      hierarchical: true
      max_hierarchy_depth: 2
```

### Describe each label

`candidate_labels` also takes a map of label to a one-line description. Jev reads the description with the label, which helps when two names are close.

```yaml content-tree llm_labeling theme={null}
    llm_labeling:
      enabled: true
      provider: typesafe
      model_name: jev-latest
      candidate_labels:
        Pharmaceutical Ads: "A prescription or over-the-counter drug, with dosage or side effects"
        Car Ads: "A car, truck or SUV for sale or lease"
        Skateboarding: "Skating in parks, pools or on the street"
        Surfing: "Riding or learning to ride ocean waves"
        Baking: "Bread, cakes and other oven-baked food"
        Grilling: "Meat or vegetables cooked over a grill or smoker"
      labeling_inputs:
        input_mappings:
          - {input_key: text, source_type: payload, path: text}
```

### Let a generative model name the clusters

Without `candidate_labels`, a generative model writes a label and a summary for each cluster. The walk shows the summary to Jev as the option's description, which helps routing.

```yaml content-tree llm_labeling 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: text}
```

### Search first, then keep hits in the chosen clusters

The member copies in `content-tree` carry their source vectors, so a `feature_search` stage can run before the walk. `agent_search` then keeps the documents inside the chosen clusters, in search order, and drops centroids.

```yaml browse-content-tree stages theme={null}
    stages:
      - stage_name: search
        stage_id: feature_search
        parameters:
          searches:
            - feature_uri: "mixpeek://text_extractor@v1/multilingual_e5_large_instruct_v1"
              query:
                input_mode: text
                value: "{{INPUT.query}}"
              top_k: 50
          final_top_k: 50
      - stage_name: browse
        stage_id: agent_search
        parameters:
          strategy: cluster_navigation
          model_name: jev-latest
          timeout_seconds: 20
          cluster_navigation:
            beam_width: 2
            max_leaf_clusters: 2
```

> [!WARNING]
>
> Do not set `enrich_source_collection: true` on the cluster for this. With it, the run writes `cluster_id` onto the source documents and creates no output collection, so there are no centroid documents for the walk to read.

### Keep the tree current

A cluster run is a snapshot. Execute the cluster again after a batch of new objects is processed, as in [Run the cluster](#run-the-cluster).


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