Installation

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

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

Install with the gh extension
gh skills-hub install elasticsearch-index-design

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

Download and extract to your repository:

.github/skills/elasticsearch-index-design/

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

Skill Files (4)

SKILL.md 12.1 KB
---
name: elasticsearch-index-design
description: >
  Design and review Elasticsearch index mappings for stated access patterns: correct
  field types, text+keyword multi-fields, doc_values tuning, mapping-explosion avoidance,
  and explicit shard settings. Use when creating a new index, reviewing a mapping
  for storage or query performance, fixing wrong field types, or when the user asks
  which type to use for search, filter, sort, or aggregation on a field.
metadata:
  author: elastic
  version: 0.1.0
  universal: true
compatibility: Elasticsearch 8.x or 9.x, self-managed, Elastic Cloud Hosted, or Elastic
  Cloud Serverless; explicit shard and replica settings apply to self-managed and
  Elastic Cloud Hosted only (managed internally on Serverless). Requires the `elastic`
  CLI ≥ 0.2 with `stack es` support.
---

# Elasticsearch Index Design

Design explicit index mappings from access patterns, review existing mappings for type and storage mistakes, and apply
corrections through a new index plus reindex when field types must change.

<!-- 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. **Gather access patterns per field.** Before choosing types, list how each field is used. For every field capture:
   - **Search** — full-text match, phrase, relevance scoring?
   - **Filter** — exact term, terms set, prefix?
   - **Aggregate** — terms, cardinality, histogram, stats?
   - **Sort** — ascending/d descending in result sets?
   - **Retrieve only** — returned in `_source` but never queried?

   The decision: classify each field into one primary access pattern (search, exact, numeric metric, date, boolean,
   structured object, or retrieve-only). Missing access-pattern data is a blocker — ask the user rather than guessing.
   Call `GET /` to confirm connectivity; when reviewing an existing index, call `GET /{index}/_mapping` to ground the
   discussion in the current mapping.

2. **Choose field types from access patterns.** Map each field to the minimal type set that satisfies its pattern. Read
   [Field Type Decisions](references/field-type-decisions.md) and
   [Multi-Field Patterns](references/multi-field-patterns.md) before proposing mappings.

   Key judgments:

   | Pattern                                         | Mapping                                                      |
   | ----------------------------------------------- | ------------------------------------------------------------ |
   | Full-text search only                           | `text` (no keyword sub-field)                                |
   | Filter / agg / sort only                        | `keyword` (not `text`)                                       |
   | Full-text search **and** sort or aggregation    | `text` with `fields.keyword` multi-field                     |
   | Decimal price or metric                         | `double`, `float`, or `scaled_float` — not `text` or integer |
   | Timestamp                                       | `date`                                                       |
   | True/false flag                                 | `boolean`                                                    |
   | Free-form key/value map with many distinct keys | `flattened` — not dynamic `object`                           |

   **Multi-field rule:** When a field must be searchable **and** sortable/aggregatable (e.g. product `name`), map it as
   `text` with a `keyword` sub-field — search on `name`, sort and aggregate on `name.keyword`. Mapping as only `text` or
   only `keyword` is wrong for that combined pattern.

   **Explicit mapping rule:** For new indices, always define mappings explicitly with `PUT /{index}`. Do not rely on
   dynamic mapping for production indices — the first document can lock in wrong types (strings as `text`, ambiguous
   numbers as `keyword`).

   **Index settings:** Set deliberate `number_of_shards` and `number_of_replicas` in the same `PUT /{index}` request
   when the deployment allows it (Self-Managed / Elastic Cloud Hosted). On Serverless, omit shard and replica counts
   (Elastic manages them); still supply explicit mappings. State chosen values or document that defaults apply.

   Example — `products` index optimized for search plus sort/agg on name:

   ```json
   {
     "settings": {
       "number_of_shards": 1,
       "number_of_replicas": 1
     },
     "mappings": {
       "properties": {
         "name": {
           "type": "text",
           "fields": {
             "keyword": { "type": "keyword", "ignore_above": 256 }
           }
         },
         "price": { "type": "double" },
         "created": { "type": "date" },
         "in_stock": { "type": "boolean" }
       }
     }
   }
   ```

   Create with `PUT /products` passing the `settings` and `mappings` blocks. Verify with `GET /products/_mapping`.

3. **Guard against mapping explosion and storage bloat.** On high-volume indices, type mistakes multiply cost. Read
   [Mapping Explosion and Storage Bloat](references/mapping-explosion.md) and apply these review checks:
   - **Analyzed-but-not-searched fields** — Fields used only for filter and aggregation (`url`, HTTP `status_code`,
     `tags`, IDs) must be `keyword`, not `text`. `text` wastes space; aggregations on `text` require fielddata or a
     `.keyword` sub-field that should not exist if the field is not searched.
   - **`message.keyword` without `ignore_above`** — A keyword sub-field on a large full-text body indexes the entire raw
     string as one term. Flag this anti-pattern; remove the sub-field when only full-text search is needed, or add
     `ignore_above` when a bounded exact-match sub-field is truly required.
   - **Dynamic free-form objects** — `object` with `"dynamic": true` on user-supplied key/value data with thousands of
     distinct keys causes **mapping explosion**. Recommend `flattened` (or strict dynamic / allowlist strategy).
   - **`doc_values: false`** — On fields retrieved in hits but never sorted, aggregated, or filtered (e.g. display-only
     `session_id`), set `"doc_values": false` on `keyword` to save disk at scale.
   - **`scaled_float`** — For metrics with bounded precision (e.g. `response_time_ms`), prefer `scaled_float` with an
     appropriate `scaling_factor` over plain `float`/`double` when storage dominates.

   Prefer `"dynamic": "strict"` on the root mapping unless unknown fields are an explicit requirement.

4. **Apply design: create new index and reindex when types change.** Elasticsearch **cannot** change an existing field's
   type in place. When review finds wrong types (text→keyword, object→flattened, float→scaled_float, doc_values changes
   on existing fields), state clearly that fixes require a **new index** and **reindex** — not a mapping update on the
   live index.

   Workflow for correcting an existing high-volume index such as `events`:
   1. **Design the corrected mapping** on a new index name (e.g. `events-v2`) incorporating all fixes from steps 2–3.
   2. **Create the destination** with `PUT /events-v2` and the full corrected `mappings` (and `settings` where
      applicable).
   3. **Copy documents** with `POST /_reindex` — for large indices use `wait_for_completion=false` and track the task.
      Source: `{ "index": "events" }`, destination: `{ "index": "events-v2" }`.
   4. **Verify** with `GET /events-v2/_count` (compare to source count) and `GET /events-v2/_mapping` (confirm types).
   5. **Cut over** reads and writes (index alias swap or application config) after validation.

   Example corrected excerpt for the `events` review pattern:

   ```json
   {
     "mappings": {
       "properties": {
         "@timestamp": { "type": "date" },
         "event_id": { "type": "keyword" },
         "session_id": { "type": "keyword", "doc_values": false },
         "url": { "type": "keyword" },
         "status_code": { "type": "keyword" },
         "response_time_ms": { "type": "scaled_float", "scaling_factor": 100 },
         "tags": { "type": "keyword" },
         "message": { "type": "text" },
         "labels": { "type": "flattened" }
       }
     }
   }
   ```

   Do not attempt in-place mapping fixes for these type changes — they are rejected or leave data inconsistent. For
   greenfield indices, a single `PUT /{index}` before first ingest avoids reindex entirely.

## Review checklist

When the user supplies a mapping JSON and usage notes, walk this checklist in order:

1. Match each field's type to its stated access pattern (see step 2).
2. Flag `text` on filter/agg-only fields; flag missing multi-fields where search and sort/agg share one logical field.
3. Flag `message.keyword` (or similar) without `ignore_above` on large analyzed text.
4. Flag dynamic `object` on high-cardinality free-form maps; recommend `flattened`.
5. Propose retrieve-only and numeric storage optimizations (`doc_values: false`, `scaled_float`).
6. State that type changes require a new index and `POST /_reindex`, then show the corrected mapping and reindex plan.

## Examples

**"Users search product names and also sort and aggregate on them"** — one logical field, two access patterns, so use a
`text` field with a `keyword` multi-field:

```json
{
  "mappings": {
    "properties": {
      "product_name": { "type": "text", "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } } }
    }
  }
}
```

**"A `status` field is only ever filtered and aggregated, never full-text searched"** — use `keyword`, not `text`:

```json
{ "mappings": { "properties": { "status": { "type": "keyword" } } } }
```

**"Free-form `labels` object with unbounded keys"** — avoid mapping explosion with `flattened`:

```json
{ "mappings": { "properties": { "labels": { "type": "flattened" } } } }
```

## Guidelines

- **Minimal mapping** — Map only what access patterns require; every sub-field and analyzed form adds indexed data.
- **Never guess access patterns** — Wrong type choice is expensive to fix at scale.
- **Verify after create** — Always confirm with `GET /{index}/_mapping`; use `GET /{index}/_count` after reindex.
- **Cross-skill boundary** — Copying documents between indices is `POST /_reindex` (see the reindex skill for slicing,
  throttling, and task tracking). Loading files into a new index is bulk ingest, not index design.

## Reference material

- [Field Type Decisions](references/field-type-decisions.md) — access-pattern-to-type table and common mistakes
- [Multi-Field Patterns](references/multi-field-patterns.md) — text+keyword, `ignore_above`, anti-patterns
- [Mapping Explosion and Storage Bloat](references/mapping-explosion.md) — `flattened`, `doc_values`, dynamic objects

## Operations

| HTTP API (shorthand)                       | `elastic` CLI command                                                                 |
| ------------------------------------------ | ------------------------------------------------------------------------------------- |
| `GET /`                                    | `elastic es info`                                                                     |
| `GET /{index}/_mapping`                    | `elastic es indices get-mapping --index '<index>'`                                    |
| `PUT /{index}`                             | `elastic es indices create --index '<index>' --mappings '<json>' --settings '<json>'` |
| `POST /_reindex`                           | `elastic es reindex --source '<json>' --dest '<json>'`                                |
| `POST /_reindex?wait_for_completion=false` | `elastic es reindex --wait-for-completion false --source '<json>' --dest '<json>'`    |
| `GET /{index}/_count`                      | `elastic es count --index '<index>'`                                                  |
references/
field-type-decisions.md 5.7 KB
# Field Type Decisions

Map each field to a type based on **how queries use it**, not how values look in JSON. A value that resembles a number
but is only ever filtered with exact match belongs in `keyword`, not `long`.

## Access pattern → type

| Access pattern                                       | Primary type                          | Notes                                                                                                            |
| ---------------------------------------------------- | ------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
| Full-text search (match, phrase, relevance)          | `text`                                | Analyzed; supports scoring. Cannot sort or aggregate without `fielddata` (avoid).                                |
| Exact filter, terms agg, sort                        | `keyword`                             | Not analyzed; default for IDs, enums, URLs, HTTP status codes, tags.                                             |
| Full-text search **and** sort/agg on same field      | `text` + `fields.keyword` multi-field | Search `name`; sort/agg on `name.keyword`.                                                                       |
| Integer counter / ID (numeric range or sum)          | `long` or `integer`                   | Use when values are true numbers and math/range queries apply.                                                   |
| Decimal metric (aggregations, range filters)         | `double`, `float`, or `scaled_float`  | Prefer `scaled_float` with an appropriate `scaling_factor` when precision is fixed and storage matters at scale. |
| Timestamp / date histogram                           | `date`                                | Accepts ISO-8601 and common date formats.                                                                        |
| Boolean flag                                         | `boolean`                             | Filter only; do not map as `keyword` unless the user explicitly wants string semantics.                          |
| Free-form key/value map (many distinct keys)         | `flattened`                           | Safer than `object` with `dynamic: true` at high cardinality.                                                    |
| Structured nested object (fixed schema)              | `object` or `nested`                  | Use `nested` when independent queries on array elements require it.                                              |
| Retrieve in `_source` only (never filter, sort, agg) | `keyword` with `"doc_values": false`  | Saves disk on high-volume indices; field still appears in search hits.                                           |

## Common mistakes

| Mistake                                                     | Why it hurts                                                                                    | Fix                                                            |
| ----------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | -------------------------------------------------------------- |
| `text` on filter-only fields (`url`, `status_code`, `tags`) | Aggregations and sorting require `.keyword` or fielddata; wastes index space on analyzed tokens | Use `keyword`                                                  |
| `keyword` only on a field that needs full-text search       | No relevance search; wildcard queries are slow                                                  | Use `text`, or `text` + `keyword` multi-field                  |
| `text` only on a field that must also be sorted/aggregated  | Sort/agg fail or require expensive fielddata                                                    | Add `fields.keyword` sub-field                                 |
| Dynamic mapping on first document                           | Wrong type locks in (e.g. `"123"` → `text`); changing type later requires reindex               | Define explicit mapping with `PUT /{index}` before bulk ingest |
| `integer` for currency or prices with decimals              | Precision loss                                                                                  | Use `double`, `float`, or `scaled_float`                       |

## Numeric precision

| Scenario                                                          | Recommended type                            |
| ----------------------------------------------------------------- | ------------------------------------------- |
| General decimal (unknown precision)                               | `double` or `float`                         |
| Fixed decimal places (e.g. currency to cents, latency to 0.01 ms) | `scaled_float` with `scaling_factor` = 10^n |
| Counters, document counts                                         | `long`                                      |

## Dates and booleans

- **Dates:** Map as `date`. Bulk and query values should use ISO-8601 (`2024-03-15` or full datetime with timezone).
- **Booleans:** Map as `boolean` with JSON `true`/`false`. String `"true"`/`"false"` indexed dynamically often becomes
  `keyword`.

## Type changes are not in-place

Elasticsearch forbids changing an existing field's type. When review finds wrong types:

1. Create a **new** index (or versioned name such as `events-v2`) with `PUT /{new_index}` and the corrected mapping.
2. Copy documents with `POST /_reindex` from the old index to the new one.
3. Verify with `GET /{new_index}/_count` and `GET /{new_index}/_mapping`.
4. Switch reads/writes (alias swap or application config) after validation.

Do not attempt to fix type mismatches with mapping updates on the live index — they are rejected or leave data
inconsistent.
mapping-explosion.md 3.9 KB
# Mapping Explosion and Storage Bloat

Mapping explosion occurs when Elasticsearch discovers unbounded distinct field names — often from dynamic `object`
mappings on user-supplied keys. Each new field consumes cluster state and disk; at billions of documents the cost is
severe.

## Dynamic objects are high risk

```json
{
  "labels": {
    "type": "object",
    "dynamic": true
  }
}
```

When `labels` is free-form key/value data with **thousands of distinct keys** across the index, every new key becomes a
new mapped field. Cluster state grows without bound; queries slow; index operations may fail when field limits are hit.

**Recommendation:** Replace with `flattened`:

```json
{
  "labels": {
    "type": "flattened"
  }
}
```

`flattened` treats the whole object as a single field with limited sub-key indexing — suitable for high-cardinality,
schema-less metadata used mainly for filtering (`labels.environment`, `labels.team` style queries in Query DSL).

## Alternatives when `flattened` is not enough

| Strategy                                            | When to use                                                    |
| --------------------------------------------------- | -------------------------------------------------------------- |
| `flattened`                                         | Arbitrary key/value maps, moderate query needs                 |
| Index only an allowlist of keys via ingest pipeline | Known subset of label keys must be first-class fields          |
| Separate "labels" index                             | Extreme cardinality; join or lookup at query time              |
| `"dynamic": "strict"` on parent object              | Reject documents with unknown keys to prevent silent explosion |

## `doc_values: false` for retrieve-only fields

`doc_values` power sorting, aggregations, and most field-centric queries. Fields loaded only in `_source` (display in
UI, never filtered or aggregated) can disable them:

```json
{
  "session_id": {
    "type": "keyword",
    "doc_values": false
  }
}
```

**Requirements before disabling:**

- Field is never used in sort, aggregation, `terms` query, or runtime field inputs that need doc values.
- Field is still returned in search hits via `_source`.

On high-volume indices, `doc_values: false` on large retrieve-only keyword fields materially reduces storage.

## Storage-oriented numeric choices

| Field role                              | Bloated choice    | Leaner choice                              |
| --------------------------------------- | ----------------- | ------------------------------------------ |
| Latency / duration with fixed precision | `float`           | `scaled_float` with tuned `scaling_factor` |
| Currency to cents                       | `double`          | `scaled_float`, `scaling_factor: 100`      |
| HTTP status (filter/agg only)           | `text` (analyzed) | `keyword` or `short` if numeric            |

## Guardrails in explicit mappings

When designing or reviewing mappings:

1. Set `"dynamic": "strict"` (or `false`) on the root or sensitive objects unless unknown fields are intentional.
2. Avoid `text` on fields that are never full-text searched.
3. Avoid keyword sub-fields on large analyzed bodies without `ignore_above`.
4. Prefer `flattened` over dynamic `object` for user-supplied maps.
5. Audit mapping size with `GET /{index}/_mapping` and watch total field count against cluster
   `index.mapping.total_fields.limit`.

## Fixing explosion or bloat on a live index

Mapping parameter tweaks that do not change field **type** (e.g. adding `ignore_above` to a new sub-field only on new
indices) still require a new index when existing field types must change. For explosion remediation:

1. Design corrected mapping on a **new** index (`events-v2`, or a dated backing index).
2. Reindex with `POST /_reindex`.
3. Verify field count and document count before cutover.

Type and structural fixes cannot be applied in place on a high-volume production index.
multi-field-patterns.md 3.1 KB
# Multi-Field Patterns

Multi-fields let one logical field support more than one access pattern by indexing the same value under different types
or analyzers.

## Text + keyword (search and sort/aggregate)

Use when users **search** full text on a field **and** sort, aggregate, or filter with exact values on the same field.

```json
{
  "name": {
    "type": "text",
    "fields": {
      "keyword": {
        "type": "keyword",
        "ignore_above": 256
      }
    }
  }
}
```

- Queries: full-text on `name`; term filter, `terms` aggregation, and sort on `name.keyword`.
- Mapping **only** `text` breaks sort/aggregation. Mapping **only** `keyword` breaks relevance search.

Apply the same pattern to product titles, descriptions, and any "searchable but also facetable" string field.

## When not to add a keyword sub-field

| Situation                                                         | Recommendation                                                      |
| ----------------------------------------------------------------- | ------------------------------------------------------------------- |
| Field is full-text searched only (`message` in log indices)       | Map as `text` **without** a `.keyword` sub-field                    |
| Field is filter/agg/sort only (`url`, `status_code`, `tags`, IDs) | Map as `keyword` only — no `text` parent                            |
| High-cardinality full-text body (log message, article body)       | Do **not** add `message.keyword` unless exact-match use case exists |

## The `ignore_above` anti-pattern

Adding a `keyword` sub-field to a large analyzed text field **without** `ignore_above` indexes the entire raw string as
a single keyword term. On high-volume indices this causes:

- Bloated terms dictionary and excessive disk use
- Risk of **document parsing exceptions** when a single term exceeds Lucene's term byte limit (~32 KB)

**Anti-pattern:**

```json
{
  "message": {
    "type": "text",
    "fields": {
      "keyword": { "type": "keyword" }
    }
  }
}
```

**Fixes (pick one based on access pattern):**

1. **Full-text only** — remove the sub-field; keep `"type": "text"`.
2. **Occasional exact match on a prefix** — add `"ignore_above": 256` (or another bound matching max exact-match length)
   on the keyword sub-field.
3. **Structured extraction** — parse identifiers (request ID, error code) into dedicated `keyword` fields at ingest
   instead of keyword-indexing the whole message.

## Other multi-field variants

| Pattern                                                    | Use case                                             |
| ---------------------------------------------------------- | ---------------------------------------------------- |
| `text` + `keyword`                                         | Search + sort/agg (most common)                      |
| `text` with different analyzers (`fields.en`, `fields.fr`) | Language-specific search on same source value        |
| `keyword` + `text` sub-field (`fields.search`)             | Exact ID field with optional secondary search (rare) |

Prefer the simplest mapping that satisfies stated access patterns — extra sub-fields multiply indexed data.

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