Installation

Install as Agent Plugin Recommended
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install elasticsearch-reindex@skills-hub

Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled). Plugin elasticsearch-reindex v1.0.0 follows the Agent Plugins spec.

Install with the gh extension
gh skills-hub install elasticsearch-reindex

Don't have the extension? Run gh extension install samueltauil/skills-hub first.

Download and extract to your repository:

.github/skills/elasticsearch-reindex/

Extract the ZIP to .github/skills/ in your repo. The folder name must match elasticsearch-reindex for Copilot to auto-discover it.

Skill Files (5)

SKILL.md 12.6 KB
---
name: elasticsearch-reindex
description: >
  Guide Elasticsearch reindex for performance: local and remote, slicing, throttling,
  task API. Use when copying or migrating indices, changing mappings, or transforming
  during reindex.
metadata:
  author: elastic
  version: 0.2.0
  universal: true
compatibility: Elasticsearch 8.x or 9.x, self-managed, Elastic Cloud Hosted, or Elastic
  Cloud Serverless; local reindex works on all deployment types, while remote reindex
  requires host allowlisting on self-managed / Elastic Cloud Hosted (Serverless supports
  Elastic Cloud Hosted remotes only, Tech Preview). Requires the `elastic` CLI ≥ 0.2
  with `stack es` support.
---

# Elasticsearch Reindex

Copy documents from source indices or data streams to a destination using `POST /_reindex`. An expert reindex workflow
prepares the destination explicitly, chooses local versus remote execution, filters at the source when only a subset is
needed, runs long copies asynchronously, tracks the task to completion, and verifies the destination document count
before reporting results.

<!-- begin-partial: preamble -->

## Environment Configuration

This skill executes Elasticsearch operations through the `elastic` CLI. If the
[`elastic` CLI](https://github.com/elastic/cli#configuration) is not installed, tell the user what it is needed for. Do
not guess credentials, call the HTTP API directly, or attempt other workarounds.

This skill references operations in HTTP-shorthand form (e.g., `GET /`, `GET /_cat/indices`, `GET /{index}/_mapping`,
`GET /{index}/_settings/index.mode`, `POST /_query`). The [Operations](#operations) table at the end of this document
maps each shorthand to the equivalent `elastic` CLI command — always use the CLI rather than calling the HTTP API
directly.

<!-- end-partial: preamble -->

## Process

1. **Confirm connectivity and deployment type.** Call `GET /`. Read `build_flavor` and `version.number` to know whether
   shard, replica, and cluster-settings APIs are available (Serverless manages shards/replicas internally and blocks
   most `_cluster/*` APIs). The decision: continue only when the cluster is reachable. If the call fails, stop — do not
   guess endpoints or credentials.

2. **Decide local versus remote reindex.** Compare where the source and destination live.
   - **Same cluster** — use local reindex: `source.index` and `dest.index` only. Do **not** add `source.remote` when
     both indices are on the cluster you are connected to.
   - **Different cluster** — use reindex from remote: add `source.remote` with the remote cluster URL and credentials.
     Remote reindex does not support slicing; compensate with query-based partitioning (date ranges, term filters)
     across parallel requests. Confirm the remote host is allowlisted on Self-Managed / ECH (`reindex.remote.whitelist`
     in cluster config); Serverless manages allowlisting internally (ECH remotes only, Tech Preview).

   Data needed: source index name(s), destination index name, and whether they share a cluster.

3. **Inspect the source — never guess field names or counts.** Call `GET /{source}/_mapping` to ground field names and
   types. Call `GET /{source}/_count` (or `GET /_cat/count/{source}?h=count` on Self-Managed / ECH) to learn how many
   documents exist.

   The decision: **full copy** versus **filtered subset**.
   - Full copy — omit `source.query` (match-all behavior).
   - Filtered subset — add `source.query` with Query DSL. For time ranges, use a `range` filter on the timestamp field
     (commonly `@timestamp`), e.g. `"gte": "2025-01-01", "lt": "2025-02-01"` for January 2025. Do **not** run a
     full-index copy when the user asked for a date range or other filter.

   Data needed: the user's filter criteria and the mapping-confirmed field names.

4. **Prepare the destination index before copying.** `_reindex` does **not** copy mappings, shard counts, or analyzers.
   Create the destination with explicit settings and mappings derived from the source mapping via `PUT /{dest}`.
   - On Self-Managed / ECH: set `number_of_replicas: 0` and `refresh_interval: "-1"` on the destination during the copy
     for write throughput; restore production values afterward with `PUT /{dest}/_settings`.
   - On Serverless: omit `number_of_shards` and `number_of_replicas` (managed by Elastic); you may set
     `refresh_interval: "-1"` during the copy.
   - For **data stream** destinations: ensure an index template with `data_stream: {}` exists, create the data stream,
     and set `dest.op_type` to `"create"` (append-only).

   The decision: create/prepare the target rather than relying on auto-creation with dynamic mapping. Wrong or missing
   mappings cause partial failures or silent type coercion.

   Data needed: destination name, corrected or compatible mappings, and deployment-specific settings constraints.

5. **Build and submit the reindex request.** Call `POST /_reindex?wait_for_completion=false` for any copy that may take
   more than a few seconds or when the user says the index is large — the response returns a **task id** immediately
   instead of blocking.

   Request body essentials:
   - `source.index` — source index or data stream (correct name, not reversed with `dest.index`).
   - `dest.index` — prepared destination from step 4.
   - `source.query` — include only when step 3 chose a filtered subset.
   - `conflicts: "proceed"` — when retrying a partially complete reindex.
   - Optional tuning: `source.size` (batch size), `requests_per_second` (throttle), `slices=auto` on local reindex only
     (parallelize per primary shard — never for remote), `scroll` (increase keep-alive on slow clusters), `max_docs`
     (test runs), `script` (transform), `dest.pipeline` (ingest enrichment).

   Example filtered subset (January 2025 only):

   ```json
   {
     "source": {
       "index": "eval-reindex-src",
       "query": {
         "range": {
           "@timestamp": { "gte": "2025-01-01", "lt": "2025-02-01" }
         }
       }
     },
     "dest": { "index": "eval-reindex-jan" }
   }
   ```

   Do **not** reach for `_split`, `_shrink`, or snapshot/restore when the task is a filtered subset copy or a straight
   document migration — those APIs solve different problems.

6. **Track the task to completion.** Store the task id from the reindex response. Poll `GET /_tasks/{task_id}` until
   `completed` is `true`. Read `status.total`, `status.created`, and `response.failures`. On Self-Managed / ECH you may
   also list active reindex tasks with `GET /_tasks?actions=*reindex&detailed`; on Serverless, query by task id only
   (list/cancel are not available). Adjust throttling mid-flight with
   `POST /_reindex/{task_id}/_rethrottle?requests_per_second=N` without canceling.

7. **Verify and report the destination count.** Call `GET /{dest}/_count` (works on all deployment types). On
   Self-Managed / ECH you may also use `GET /_cat/count/{dest}?h=count`. Compare source filter expectations to the
   destination count. Report the **exact** count from the destination — do not estimate or guess.

   After a successful full copy, restore production settings on the destination with `PUT /{dest}/_settings` (replicas
   and refresh interval on Self-Managed / ECH; refresh interval only on Serverless).

## Deployment constraints

| Capability                  | Self-Managed / ECH | Serverless                                |
| --------------------------- | ------------------ | ----------------------------------------- |
| Local reindex               | Full support       | Full support                              |
| Reindex from remote         | Full support       | Tech Preview — ECH remotes only           |
| `number_of_shards/replicas` | User-configurable  | Managed — omit on index creation          |
| `slices=auto` (local only)  | Supported          | Supported for local reindex               |
| `GET /_cat/count/{index}`   | Supported          | Not available — use `GET /{index}/_count` |
| `GET /_tasks` (list/cancel) | Full               | Get by task id only                       |
| `PUT /_cluster/settings`    | Supported          | Blocked                                   |
| `_split` / `_shrink`        | Supported          | Not available                             |

## Consider alternatives first

- **Runtime fields** — fix field-type mismatches or add computed fields without reindexing when stored values need not
  change.
- **Aliases** — redirect queries transparently; combine with reindex for zero-downtime mapping changes.
- **Snapshot and restore** (Self-Managed / ECH) — faster whole-index transfer when no transformation is needed.

See the decision tree in [references/patterns.md](references/patterns.md#decision-tree-do-i-need-to-reindex).

## Reference material

- [API parameter reference](references/api-reference.md) — full `POST /_reindex` body and query parameters
- [Multi-step patterns](references/patterns.md) — mapping changes, remote migration, merge, ingest pipeline, performance
- [Tuning](references/tuning.md) — batch size (`source.size`), timestamps, versioning
- [Troubleshooting](references/troubleshooting.md) — mapping conflicts, scroll timeouts, count mismatches

## Examples

**"Copy `logs-2024` into a new index with a corrected mapping"** — create the destination first, then reindex:

```json
POST /_reindex
{ "source": { "index": "logs-2024" }, "dest": { "index": "logs-2024-v2" } }
```

**"Reindex a large index in parallel and throttle it"** — slice automatically and cap the request rate:

```json
POST /_reindex?slices=auto&requests_per_second=2000
{ "source": { "index": "events" }, "dest": { "index": "events-v2" } }
```

**"Migrate only recent documents"** — filter the source with a query:

```json
POST /_reindex
{
  "source": { "index": "metrics", "query": { "range": { "@timestamp": { "gte": "now-30d" } } } },
  "dest": { "index": "metrics-recent" }
}
```

## Guidelines

- **Confirm deployment type first.** Call `GET /` and read `build_flavor`; shard, replica, cluster-settings, and task
  APIs differ between Self-Managed / ECH and Serverless (see Deployment constraints).
- **Prefer an alternative when it fits.** Runtime fields, aliases, or snapshot-and-restore often avoid a full reindex.
- **Tune the destination for the copy.** On Self-Managed / ECH set `number_of_replicas: 0` and `refresh_interval: "-1"`
  during the copy, then restore production settings afterward; on Serverless these are managed.
- **Parallelize large copies.** Use `slices=auto` for local reindex and throttle with `requests_per_second` to protect
  the cluster.
- **Run big jobs asynchronously.** Submit with `wait_for_completion=false` and poll the task instead of blocking.
- **Verify by count.** Compare the source filter expectation to the exact destination `GET /{dest}/_count` — never
  estimate.

## Operations

| HTTP API (shorthand)                                         | `elastic` CLI command                                                                 |
| ------------------------------------------------------------ | ------------------------------------------------------------------------------------- |
| `GET /`                                                      | `elastic es info`                                                                     |
| `GET /{index}/_mapping`                                      | `elastic es indices get-mapping --index '<index>'`                                    |
| `GET /{index}/_count`                                        | `elastic es count --index '<index>'`                                                  |
| `GET /_cat/count/{index}?h=count`                            | `elastic es cat count --index '<index>' --h count`                                    |
| `PUT /{index}`                                               | `elastic es indices create --index '<index>' --mappings '<json>' --settings '<json>'` |
| `PUT /{index}/_settings`                                     | `elastic es indices put-settings --index '<index>' --settings '<json>'`               |
| `POST /_reindex?wait_for_completion=false`                   | `elastic es reindex --wait-for-completion false --source '<json>' --dest '<json>'`    |
| `GET /_tasks/{task_id}`                                      | `elastic es tasks get --task-id '<task_id>'`                                          |
| `GET /_tasks?actions=*reindex&detailed`                      | `elastic es tasks list --actions '*reindex' --detailed`                               |
| `POST /_tasks/{task_id}/_cancel`                             | `elastic es tasks cancel --task-id '<task_id>'`                                       |
| `POST /_reindex/{task_id}/_rethrottle?requests_per_second=N` | `elastic es reindex-rethrottle --task-id '<task_id>' --requests-per-second <N>`       |
references/
api-reference.md 14.2 KB
# Reindex API Reference

Complete parameter reference for `POST /_reindex`. See the [main skill file](../SKILL.md) for usage guidance and best
practices.

## Endpoint

```text
POST /_reindex
POST /_reindex?wait_for_completion=false
POST /_reindex?wait_for_completion=false&slices=auto
```

## Query Parameters

| Parameter             | Type                | Default          | Description                                                                                                            |
| --------------------- | ------------------- | ---------------- | ---------------------------------------------------------------------------------------------------------------------- |
| `wait_for_completion` | boolean             | `true`           | Set to `false` to return a task ID immediately. The reindex runs in the background and results are stored in `.tasks`. |
| `requests_per_second` | float               | `-1` (unlimited) | Throttle indexing rate. Each batch pauses to maintain this rate. Set to `-1` to disable.                               |
| `slices`              | integer or `"auto"` | `1`              | Number of parallel slices. `auto` uses one slice per primary shard. Not supported for remote reindex.                  |
| `scroll`              | duration            | `5m`             | Keep-alive for the scroll context used to read from the source. Increase for slow clusters.                            |
| `timeout`             | duration            | —                | Timeout for the entire operation when running synchronously.                                                           |
| `refresh`             | boolean             | `false`          | Refresh the destination index after the reindex completes.                                                             |

## Request Body

### Top-level fields

| Field       | Type    | Required | Default   | Description                                                                                                                                                       |
| ----------- | ------- | -------- | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `conflicts` | string  | No       | `"abort"` | `"abort"` stops on the first version conflict. `"proceed"` skips conflicting documents and continues. Use `"proceed"` when retrying a partially-complete reindex. |
| `max_docs`  | integer | No       | —         | Maximum number of documents to reindex. Useful for testing a configuration on a small sample before running at full scale.                                        |
| `script`    | object  | No       | —         | Painless script to transform each document. See [Script object](#script-object).                                                                                  |

### `source` object

| Field     | Type            | Required | Default    | Description                                                                                                 |
| --------- | --------------- | -------- | ---------- | ----------------------------------------------------------------------------------------------------------- |
| `index`   | string or array | Yes      | —          | Source index name, alias, data stream, or list of indices.                                                  |
| `query`   | object          | No       | match_all  | Query DSL to filter source documents.                                                                       |
| `_source` | array           | No       | all fields | List of fields to include in each document.                                                                 |
| `size`    | integer         | No       | `1000`     | Number of documents per scroll batch. Reduce for large documents; increase (up to ~5000) for small ones.    |
| `slice`   | object          | No       | —          | Manual slicing: `{ "id": 0, "max": 4 }`. Prefer automatic slicing via the `slices` query parameter instead. |
| `remote`  | object          | No       | —          | Remote cluster connection. See [`source.remote` object](#sourceremote-object).                              |

### `source.remote` object

| Field             | Type     | Required | Default | Description                                                                                                                                               |
| ----------------- | -------- | -------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `host`            | string   | Yes      | —       | Full URL including scheme, host, and port (e.g., `https://remote:9200`). An optional path prefix is supported (e.g., `https://remote:9200/proxy`).        |
| `username`        | string   | No       | —       | Basic auth username for the remote cluster. Supported for the remote regardless of where the reindex runs. Always use HTTPS when credentials are present. |
| `password`        | string   | No       | —       | Basic auth password for the remote cluster.                                                                                                               |
| `api_key`         | string   | No       | —       | Base64-encoded API key. Preferred over basic auth.                                                                                                        |
| `headers`         | object   | No       | —       | Custom HTTP headers. Use `{ "Authorization": "ApiKey <value>" }` as an alternative to `api_key`.                                                          |
| `socket_timeout`  | duration | No       | `30s`   | Read timeout for each scroll request to the remote. Increase to `1m`–`5m` for slow or congested networks.                                                 |
| `connect_timeout` | duration | No       | `30s`   | TCP connection timeout. Increase when the remote is behind a load balancer.                                                                               |

### `dest` object

| Field          | Type   | Required | Default      | Description                                                                                                                                                                                                                                                        |
| -------------- | ------ | -------- | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `index`        | string | Yes      | —            | Destination index or data stream name. Create the index (or data stream via template) with explicit mappings before reindexing. When the destination is a data stream, set `op_type` to `"create"`.                                                                |
| `op_type`      | string | No       | `"index"`    | `"index"` overwrites existing documents with the same `_id`. `"create"` only creates missing documents; use with `"conflicts": "proceed"` to skip conflicts. **Required:** set to `"create"` when the destination is a data stream (data streams are append-only). |
| `pipeline`     | string | No       | —            | Name of an ingest pipeline to apply to each document during indexing.                                                                                                                                                                                              |
| `routing`      | string | No       | preserve     | `"keep"` preserves source routing (default). `"discard"` sets routing to null. `"=<value>"` sets a fixed routing value.                                                                                                                                            |
| `version_type` | string | No       | `"internal"` | `"internal"` ignores source version. `"external"` preserves source version and rejects older writes. Use `"external"` when synchronizing across clusters.                                                                                                          |

### Script object

| Field    | Type   | Description                                                                                                                                                                                                    |
| -------- | ------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `source` | string | Painless script body. Access the document via `ctx._source`. Set `ctx.op` to `"noop"` or `"delete"` to skip or remove documents. Modify `ctx._id`, `ctx._index`, `ctx._routing`, and `ctx._version` as needed. |
| `lang`   | string | Script language. Default and recommended: `"painless"`.                                                                                                                                                        |
| `params` | object | Named parameters accessible inside the script.                                                                                                                                                                 |

## Response Body

Returned when the reindex completes synchronously or when fetching a completed task via `GET _tasks/<task_id>`.

| Field                 | Type    | Description                                                                   |
| --------------------- | ------- | ----------------------------------------------------------------------------- |
| `took`                | integer | Total time in milliseconds.                                                   |
| `timed_out`           | boolean | Whether the operation timed out.                                              |
| `total`               | integer | Total documents processed (source-side).                                      |
| `created`             | integer | Documents successfully created in the destination.                            |
| `updated`             | integer | Documents updated in the destination (same `_id` existed).                    |
| `deleted`             | integer | Documents deleted by a script setting `ctx.op = "delete"`.                    |
| `batches`             | integer | Number of scroll batches pulled from the source.                              |
| `noops`               | integer | Documents skipped by a script setting `ctx.op = "noop"`.                      |
| `version_conflicts`   | integer | Version conflicts encountered. Only non-zero when `conflicts` is `"proceed"`. |
| `retries`             | object  | `{ "bulk": N, "search": N }` — retry counts for bulk and scroll operations.   |
| `failures`            | array   | List of per-document failure objects. Empty on full success.                  |
| `throttled_millis`    | integer | Total time spent waiting due to `requests_per_second` throttling.             |
| `requests_per_second` | float   | Effective requests-per-second rate.                                           |

## Related APIs

| API                | Endpoint                                                    | Purpose                                                                                               |
| ------------------ | ----------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- |
| Task status        | `GET _tasks/<task_id>`                                      | Monitor a running or completed reindex task. Works on all deployment types including Serverless.      |
| List reindex tasks | `GET _tasks?actions=*reindex&detailed`                      | List all active reindex operations. Not available in Serverless — query by task ID instead.           |
| Cancel task        | `POST _tasks/<task_id>/_cancel`                             | Cancel a running reindex. Not available in Serverless — delete the destination index to stop.         |
| Rethrottle         | `POST _reindex/<task_id>/_rethrottle?requests_per_second=N` | Adjust throttling on a running reindex without canceling.                                             |
| Count              | `GET _cat/count/<index>?h=count`                            | Verify document count after reindex. Not available in Serverless — use `GET /<index>/_count` instead. |

## `reindex.remote.whitelist` Setting

Configure in `elasticsearch.yml` on every coordinating node that may execute remote reindex requests. Accepts
comma-separated `host:port` pairs with wildcard support:

```yaml
reindex.remote.whitelist: "remote-host:9200, 10.0.0.*:9200, localhost:*"
```

This setting does not apply to Elastic Cloud Serverless — Serverless only permits remote reindex from Elastic Cloud
Hosted clusters and manages the allowlist internally.

## SSL Configuration for Remote Reindex

SSL settings for remote reindex connections are configured in `elasticsearch.yml`, not in the API request body. These
settings apply to **Self-Managed only**. On ECH, SSL is managed via the deployment configuration. On Serverless, remote
reindex SSL is managed internally by Elastic.

| Setting                               | Description                                                                 |
| ------------------------------------- | --------------------------------------------------------------------------- |
| `reindex.ssl.certificate_authorities` | List of PEM CA certificate paths.                                           |
| `reindex.ssl.certificate`             | Client certificate path for mutual TLS.                                     |
| `reindex.ssl.key`                     | Client key path for mutual TLS.                                             |
| `reindex.ssl.verification_mode`       | `full` (default), `certificate`, or `none`. Use `none` only in development. |

Secure settings (`reindex.ssl.key_passphrase`, `reindex.ssl.truststore.*`, `reindex.ssl.keystore.*`) are stored in the
Elasticsearch keystore via `elasticsearch-keystore add`.
patterns.md 15.4 KB
# Reindex Patterns

Common multi-step recipes for the Reindex API. Each pattern includes the full sequence of API calls needed.

## Pattern 1: Change Mappings on an Existing Index

Use when field types, analyzers, or tokenizers need to change on an index that already contains data. Elasticsearch does
not allow altering the mapping of an existing field — reindex into a new index with the corrected mapping, then swap an
alias to make the change transparent to clients.

### Steps

1. Create the new index with corrected mappings. On Self-Managed / ECH, include `number_of_shards` and
   `number_of_replicas: 0` for write throughput. On Serverless, omit both (managed by Elastic):

```json
PUT /my-index-v2
{
  "settings": {
    "number_of_shards": 3,
    "number_of_replicas": 0,
    "refresh_interval": "-1"
  },
  "mappings": {
    "properties": {
      "status": { "type": "keyword" },
      "message": { "type": "text", "analyzer": "standard" },
      "@timestamp": { "type": "date" }
    }
  }
}
```

1. Reindex from old to new:

```json
POST /_reindex?wait_for_completion=false&slices=auto
{
  "source": { "index": "my-index-v1" },
  "dest": { "index": "my-index-v2" }
}
```

1. Monitor until complete, then verify counts (on Serverless, use `GET /<index>/_count` instead of `_cat/count`):

```text
GET _tasks/<task_id>
GET _cat/count/my-index-v1?h=count
GET _cat/count/my-index-v2?h=count
```

1. Restore production settings (on Serverless, restore only `refresh_interval`):

```json
PUT /my-index-v2/_settings
{ "number_of_replicas": 1, "refresh_interval": "1s" }
```

1. Swap the alias atomically:

```json
POST /_aliases
{
  "actions": [
    { "remove": { "index": "my-index-v1", "alias": "my-index" } },
    { "add": { "index": "my-index-v2", "alias": "my-index" } }
  ]
}
```

1. Delete the old index once confirmed:

```json
DELETE /my-index-v1
```

## Pattern 2: Migrate Data from a Remote Cluster

Use when upgrading Elasticsearch across major versions (e.g., 7.x to 9.x) or consolidating clusters. Remote reindex does
not support slicing — partition by date range to parallelize.

### Steps

1. Confirm the remote host is allowlisted on the local cluster (`reindex.remote.whitelist` in `elasticsearch.yml`). On
   Serverless, allowlisting is managed internally and only ECH remotes are permitted (Tech Preview).

2. Create the destination index with mappings compatible with the new version.

3. Identify a good partition key. For time-series data, use `@timestamp` ranges. For entity data, use a high-cardinality
   keyword field.

4. Reindex one partition at a time (or in parallel):

```json
POST /_reindex?wait_for_completion=false
{
  "source": {
    "remote": {
      "host": "https://old-cluster:9200",
      "api_key": "base64key",
      "socket_timeout": "2m"
    },
    "index": "logs-2025.01",
    "size": 500
  },
  "dest": { "index": "logs-2025.01" }
}
```

1. Repeat for each partition. Monitor tasks and verify counts after each completes.

2. Restore replicas and refresh interval on all destination indices.

### Partition strategies

| Data shape                    | Partition key                     | Example query                                                            |
| ----------------------------- | --------------------------------- | ------------------------------------------------------------------------ |
| Time-series (logs, metrics)   | `@timestamp` range                | `"range": { "@timestamp": { "gte": "2025-01-01", "lt": "2025-02-01" } }` |
| Entity data (users, products) | Modulo on `_id` or keyword field  | `"script": { "source": "doc['user_id'].value.hashCode() % 4 == 0" }`     |
| Per-index                     | Separate request per source index | One `POST /_reindex` request per source index                            |

## Pattern 2b: Copy a Data Stream from ECH to a New Data Stream in Serverless

Use when migrating a complete data stream from Elastic Cloud Hosted (ECH) to a new data stream in a Serverless project.
The reindex request runs on Serverless and pulls from the remote ECH cluster. Data streams are append-only, so the
destination must use `op_type: "create"`.

### Steps

1. **Authenticate to Serverless with an API key.** All API calls to Serverless require an API key in the request
   headers. For the remote ECH connection you can use either an API key or basic auth (username/password) in
   `source.remote`.

2. **Create the destination data stream on Serverless.** You need an index template that has `data_stream: {}` and
   matches the data stream name, then create the data stream. On Serverless omit `number_of_shards` and
   `number_of_replicas`; you can set `refresh_interval` in the template for backing indices to tune write throughput
   during the reindex (e.g. `"-1"`), then restore it after.
   - Create an index template that matches the new data stream (e.g. `logs-myapp`) with mappings and optional
     `refresh_interval` in settings.
   - Create the data stream: `PUT _data_stream/<destination-data-stream-name>` (or let reindex create it on first
     document if the template exists and you have the required index privilege).

3. **Run reindex from remote** against the Serverless project. Set `source.remote.host` to the ECH cluster URL,
   `source.index` to the ECH data stream name, and `dest.index` to the Serverless data stream name. Use
   **`dest.op_type`: `"create"`** — required for any data stream destination because data streams are append-only.

```json
POST /_reindex?wait_for_completion=false
{
  "conflicts": "proceed",
  "source": {
    "remote": {
      "host": "https://your-ech-deployment.es.region.gcp.cloud.es.io:9243",
      "api_key": "<ECH-api-key>",
      "socket_timeout": "2m",
      "connect_timeout": "30s"
    },
    "index": "logs-myapp",
    "size": 500
  },
  "dest": {
    "index": "logs-myapp",
    "op_type": "create"
  }
}
```

1. **Parallelize with query-based partitioning** if the stream is large. Remote reindex does not support slicing. Run
   multiple reindex requests in parallel, each with a `query` that partitions the data (e.g. by `@timestamp` range).

2. **Monitor** via `GET _tasks/<task_id>` (on Serverless you get the task ID from the reindex response; list/cancel may
   not be available). **Verify document count** with `GET /<data-stream-name>/_count` on both ECH and Serverless.

3. **Restore production settings** on the destination if you set `refresh_interval` to `"-1"` in the template for the
   reindex (e.g. update the index template or apply settings to existing backing indices as supported).

## Pattern 3: Split a Large Index by Date Range

Use when a monolithic index needs to be broken into daily, weekly, or monthly indices to align with ILM policies or data
stream conventions.

### Steps

1. Create destination indices with appropriate mappings (or use an index template that matches the naming pattern).

2. Use a Painless script to route each document to the correct destination index:

```json
POST /_reindex?wait_for_completion=false&slices=auto
{
  "source": {
    "index": "monolith-index"
  },
  "dest": {
    "index": "temp"
  },
  "script": {
    "lang": "painless",
    "source": "def ts = ctx._source['@timestamp']; ctx._index = 'logs-' + ts.substring(0, 10)"
  }
}
```

This routes documents to indices named `logs-YYYY-MM-DD` based on the `@timestamp` value.

1. The destination index name in the `dest` field is overridden by the script — the `"temp"` value is never used. Ensure
   index templates cover the `logs-*` pattern so indices are created automatically with correct settings.

2. Verify document counts across all resulting indices:

```text
GET _cat/count/logs-2025-01-*?h=count
```

## Pattern 4: Merge Multiple Indices into One

Use when consolidating many small indices into a single index for simpler management or improved search performance.

### Steps

1. Create the destination index with mappings that are a superset of all source indices.

2. Handle ID collisions — documents from different source indices may share the same `_id`. Append the source index name
   to make IDs unique:

```json
POST /_reindex?wait_for_completion=false&slices=auto
{
  "conflicts": "proceed",
  "source": {
    "index": ["index-a", "index-b", "index-c"]
  },
  "dest": {
    "index": "merged-index"
  },
  "script": {
    "lang": "painless",
    "source": "ctx._id = ctx._id + '-' + ctx._index"
  }
}
```

1. If ID uniqueness is already guaranteed across sources, skip the script and reindex directly.

2. Alternatively, use `"op_type": "create"` with `"conflicts": "proceed"` to keep the first version of each document and
   skip duplicates.

## Pattern 5: Reindex through an Ingest Pipeline

Use when documents need server-side enrichment (GeoIP, user-agent parsing, enrich lookups) or structural transformation
(field removal, renaming via `rename` processor, script processor) during the copy.

### Steps

1. Create (or verify) the ingest pipeline:

```json
PUT /_ingest/pipeline/my-enrich-pipeline
{
  "description": "Add GeoIP and remove sensitive fields",
  "processors": [
    { "geoip": { "field": "client_ip" } },
    { "remove": { "field": "raw_password", "ignore_missing": true } }
  ]
}
```

1. Create the destination index.

2. Reindex with the pipeline:

```json
POST /_reindex?wait_for_completion=false&slices=auto
{
  "source": { "index": "raw-data" },
  "dest": {
    "index": "enriched-data",
    "pipeline": "my-enrich-pipeline"
  }
}
```

1. Pipeline processors run on the coordinating node's ingest thread pool. Monitor cluster load and consider
   `requests_per_second` throttling if the pipeline is CPU-intensive.

## Pattern 6: Performance-Tuned Bulk Reindex

Full recipe for reindexing a large index (100M+ documents) with all performance optimizations applied.

**Serverless note:** On Serverless, omit `number_of_shards`, `number_of_replicas`, and `index.translog.*` settings (all
managed by Elastic). Only `refresh_interval` is user-configurable. Skip the `_forcemerge` step — it is not available in
Serverless.

### Steps

1. Create the destination index tuned for write throughput. On Self-Managed / ECH use the full settings below. On
   Serverless, create the index with only `refresh_interval` in settings (omit `number_of_shards`, `number_of_replicas`,
   and `index.translog.*`):

**Self-Managed / ECH:**

```json
PUT /my-large-index-v2
{
  "settings": {
    "number_of_shards": 5,
    "number_of_replicas": 0,
    "refresh_interval": "-1",
    "index.translog.durability": "async",
    "index.translog.flush_threshold_size": "1gb"
  },
  "mappings": { }
}
```

**Serverless:**

```json
PUT /my-large-index-v2
{
  "settings": {
    "refresh_interval": "-1"
  },
  "mappings": { }
}
```

Setting `translog.durability` to `"async"` and increasing the flush threshold reduces fsync frequency (Self-Managed /
ECH only). Only use these settings during bulk ingest — restore defaults after the reindex.

1. Run the reindex with all performance options:

```json
POST /_reindex?wait_for_completion=false&slices=auto&requests_per_second=-1
{
  "conflicts": "proceed",
  "source": {
    "index": "my-large-index-v1",
    "size": 5000
  },
  "dest": {
    "index": "my-large-index-v2"
  }
}
```

1. Monitor progress:

```text
GET _tasks/<task_id>
```

Watch `status.created` and `status.total` to estimate completion time.

1. After completion, restore safe settings (on Serverless, restore only `refresh_interval`):

**Self-Managed / ECH:**

```json
PUT /my-large-index-v2/_settings
{
  "number_of_replicas": 1,
  "refresh_interval": "1s",
  "index.translog.durability": "request",
  "index.translog.flush_threshold_size": "512mb"
}
```

**Serverless:**

```json
PUT /my-large-index-v2/_settings
{
  "refresh_interval": "1s"
}
```

1. Force-merge to optimize segment count for read performance (Self-Managed / ECH only — not available in Serverless):

```text
POST /my-large-index-v2/_forcemerge?max_num_segments=1
```

1. Verify counts and swap the alias.

## Decision Tree: Do I Need to Reindex?

| Scenario                                     | Reindex needed?          | Alternative                                                                                                  |
| -------------------------------------------- | ------------------------ | ------------------------------------------------------------------------------------------------------------ |
| Change a field's data type                   | Yes                      | Runtime fields (read-only fix, no stored change)                                                             |
| Add a new field to existing documents        | Yes (if stored)          | Runtime fields or ingest pipeline on new data only                                                           |
| Change analyzer or tokenizer                 | Yes                      | —                                                                                                            |
| Change shard count                           | Yes (Self-Managed / ECH) | `_split` or `_shrink` for simple shard changes (not available in Serverless — shards are managed by Elastic) |
| Move data to another cluster                 | Yes (remote reindex)     | Snapshot/restore if no transformation needed (Self-Managed / ECH only — not user-accessible in Serverless)   |
| Consolidate many small indices               | Yes                      | —                                                                                                            |
| Fix a few incorrect documents                | No                       | `_update_by_query`                                                                                           |
| Rename an index                              | No                       | Alias swap                                                                                                   |
| Filter out deleted documents (reclaim space) | Yes                      | `_forcemerge?only_expunge_deletes=true` (partial reclaim, Self-Managed / ECH only)                           |

## Additional examples

Full request examples. See the [main skill file](../SKILL.md) for process and CLI mapping.

### Full performance-tuned local reindex

```json
POST /_reindex?wait_for_completion=false&slices=auto
{
  "conflicts": "proceed",
  "source": {
    "index": "my-index-000001",
    "size": 5000
  },
  "dest": {
    "index": "my-new-index"
  }
}
```

### Remote reindex with date-range partitioning

Run multiple requests in parallel, each covering a date range:

```json
POST /_reindex?wait_for_completion=false
{
  "source": {
    "remote": {
      "host": "https://remote-cluster:9200",
      "api_key": "<remote-api-key>",
      "socket_timeout": "2m"
    },
    "index": "logs-2025",
    "query": {
      "range": {
        "@timestamp": { "gte": "2025-01-01", "lt": "2025-02-01" }
      }
    },
    "size": 500
  },
  "dest": { "index": "logs-2025" }
}
```

### Reindex with field renaming script

```json
POST /_reindex?wait_for_completion=false
{
  "source": { "index": "events-v1" },
  "dest": { "index": "events-v2" },
  "script": {
    "lang": "painless",
    "source": "ctx._source.event_type = ctx._source.remove('type')"
  }
}
```

### Reindex through an ingest pipeline

```json
POST /_reindex?wait_for_completion=false
{
  "source": { "index": "raw-logs" },
  "dest": {
    "index": "enriched-logs",
    "pipeline": "geoip-and-useragent"
  }
}
```

### Merge multiple indices with ID collision handling

```json
POST /_reindex?wait_for_completion=false
{
  "conflicts": "proceed",
  "source": { "index": ["index-a", "index-b", "index-c"] },
  "dest": { "index": "merged-index" },
  "script": {
    "lang": "painless",
    "source": "ctx._id = ctx._id + '-' + ctx._index"
  }
}
```
troubleshooting.md 2.4 KB
# Reindex Troubleshooting

Common failure modes and how to resolve them.

## "Backend closed connection" in Kibana Dev Tools

The Kibana socket timeout (default 120 s) expired, but the reindex is still running on the cluster. Check progress with
the task API. On Self-Managed / ECH, list all reindex tasks. On Serverless, query the specific task ID returned by
`wait_for_completion=false`:

```text
GET /_tasks?actions=*reindex&detailed
GET /_tasks/{task_id}
```

## Mapping conflicts cause partial reindex

Documents fail to index when field types in source and destination do not match.

**Self-Managed / ECH** — enable debug logging to surface the exact field:

```json
PUT /_cluster/settings
{ "transient": { "logger.org.elasticsearch.action.bulk.TransportShardBulkAction": "DEBUG" } }
```

Search the Elasticsearch logs for `failed to execute bulk item` or `MapperParsingException`. Fix the destination
mapping, delete the partially-populated index, and re-run. Reset the logger afterward:

```json
PUT /_cluster/settings
{ "transient": { "logger.org.elasticsearch.action.bulk.TransportShardBulkAction": null } }
```

**Serverless** — `_cluster/settings` is not available. Instead, run a small test reindex with `max_docs` set to a low
value and inspect the task response for `failures`. Each failure object contains the field name and the mapping conflict
details.

## Scroll context lost (`search_phase_execution_exception`)

The default scroll keep-alive is 5 minutes. On slow or overloaded clusters, increase it on the reindex request:

```json
POST /_reindex?scroll=2h&wait_for_completion=false
{
  "source": { "index": "my-index" },
  "dest": { "index": "my-new-index" }
}
```

## Document count mismatch after multi-source reindex

When reindexing from multiple source indices, documents with the same `_id` overwrite each other. Append the source
index name to the ID with a script (see the merge example in [patterns.md](patterns.md)) or set `"op_type": "create"` on
the destination combined with `"conflicts": "proceed"` to keep the first-written version.

## Node connectivity errors (Self-Managed / ECH only)

`NodeNotConnectedException` indicates cluster instability unrelated to the reindex API. Verify cluster health is green,
reduce replicas on the destination index, and retry. If the problem persists, resolve the underlying connectivity issue
before attempting reindex. This error does not apply to Serverless — node management is handled by Elastic.
tuning.md 2.8 KB
# Reindex Tuning Reference

Detailed guidance for batch size and timestamp handling. See the [main skill file](../SKILL.md) for overview and
procedures.

## Choosing batch size (`source.size`)

The `source.size` field controls how many documents each scroll batch fetches. The default is `1000`. Use the following
to choose a good value.

### Estimate document size

- Use the Index Stats API (`GET /<index>/_stats?level=shards`) and divide store size by doc count for a rough
  bytes-per-document average.
- Or sample a few documents with `GET /{index}/_search?size=10` and inspect `_source` size.
- For **remote reindex**, the coordinating node uses a **100 MB** on-heap buffer per request — keep
  `(source.size × average document size)` comfortably under that (e.g. under 50–80 MB) to avoid `OutOfMemoryError`.

### Start with the default and adjust

- Start with **1000** (or **500** for remote). If you see scroll or bulk failures, OOM, or slow progress, reduce
  `source.size` (e.g. 250–500 for large docs). If documents are small (e.g. &lt; 1 KB) and the cluster is healthy, try
  increasing (e.g. 2000–5000) to reduce round-trips.

### Test with `max_docs`

Run a short reindex with `max_docs` (e.g. 10_000) at two or three different `source.size` values and compare throughput
(documents per second from the task response). Use the size that gives the best throughput without errors, then run the
full reindex with that value.

## Timestamps and versioning

Document timestamp values (e.g. `@timestamp` or other date fields) live in `_source` and are copied to the destination
unchanged unless you exclude them with `source._source` or change them in a script.

- **Destination mapping:** Ensure the destination index or data stream has a compatible mapping for each timestamp field
  (e.g. `date`). Mismatched or missing types can cause coercion or indexing errors.
- **Including timestamps when filtering `_source`:** If you use `source._source` to copy only certain fields, list every
  timestamp field you need. Omitting them drops those values and can break time-based queries, data stream routing, and
  ILM/retention.
- **Scripts:** Do not remove or overwrite timestamp fields in a script unless you intend to (e.g. to fix bad data).
  Leave them in `ctx._source` so they are written to the destination as-is.
- **Data streams:** The timestamp field (commonly `@timestamp`) is used to route documents to the correct backing index.
  Preserve it in `_source` and use a correct date mapping so documents land in the right time window.
- **Cross-cluster ordering:** To preserve the source document version when writing to the destination (e.g. to avoid
  overwriting newer with older when reindexing from remote), set **`dest.version_type`** to **`"external"`**.
  Elasticsearch will then keep the source version and reject writes that are older than the existing document.

License (Apache-2.0)

View full license text
Licensed under the Apache License, Version 2.0. See https://github.com/elastic/agent-skills/blob/main/LICENSE