Skip to content

Lesson 4 of 9 · 27m

Elasticsearch Indexing Strategy That Survives Scale

Mappings, data streams, shards, and cardinality — the index design choices that decide whether Elasticsearch is fast or constantly on fire.

Elasticsearch is a search engine first and a database only if you squint. Treating it like a bottomless document bin is how teams end up with 5,000 fields, thousands of tiny shards, and queries that time out precisely when the incident channel is watching.

Start with a data stream, not an index pile

Modern Elastic log storage belongs in data streams backed by time-series indices:

PUT _index_template/logs-app
{
  "index_patterns": ["logs-app-*"],
  "data_stream": {},
  "template": {
    "settings": {
      "index.number_of_shards": 1,
      "index.number_of_replicas": 1
    },
    "mappings": {
      "properties": {
        "@timestamp": {"type": "date"},
        "service.name": {"type": "keyword"},
        "host.name": {"type": "keyword"},
        "log.level": {"type": "keyword"},
        "trace_id": {"type": "keyword"},
        "message": {"type": "text"}
      }
    }
  }
}

keyword is exact-match and aggregation friendly. text is analyzed search. A URL path, status code, pod name, or trace ID is usually keyword. A free-form message is usually text.

Shard count is operational debt

Too many small shards waste memory and cluster state. Too few huge shards make recovery and force-merge painful. For logging, aim for shards in the tens of gigabytes, not megabytes. A one-shard-per-day habit made sense in 2016; at small volume it now creates hundreds of useless shards.

Check the damage with GET _cat/shards?v&s=index and _cat/indices before inventing a rollover policy.

Mapping explosion is cardinality's quiet cousin

Dynamic mapping is convenient until one service sends fields like user.123456.email and creates a field per user. Elasticsearch has field limits for a reason, but hitting them means the design already failed.

Control it:

"settings": {"index.mapping.total_fields.limit": 1000},
"mappings": {"dynamic": "runtime"}

or use dynamic: false for high-trust namespaces where unknown fields can be ignored.

Field notes

  • Never index request bodies by default. They are high-cardinality, sensitive, and rarely searchable in the way people imagine.
  • trace_id and span_id are the fields that make logs operationally useful. Standardize them.
  • Reindexing is possible but expensive. Changing mappings is not a casual migration.
  • One giant logs-* data stream feels convenient until retention and access control requirements diverge.

Was this lesson helpful?

Sign in to rate