RousselTMLEARNING

Article · Elasticsearch: from discovery to expertise

Elasticsearch best practices

1. Sizing indices and shards #

The most impactful setting.

Sizing rules #

Recommended shard size
Too many small shards consume memory; too large, they slow down recovery.
  • Aim for 10 to 50 GB per shard. The old rule « fewer than 20 shards per GB of heap » was withdrawn by Elastic in 8.3: instead, watch the cluster.max_shards_per_node limit and the memory actually used by mappings and fields.
  • A single primary shard is enough for small indices; avoid over-sharding.
  • Use data streams with rollover rather than a single giant index.
# Toutes les commandes utilisent HTTPS et l'authentification (ca.crt : certificat de l'autorité du cluster)
export ES_PASSWORD='...'
curl --cacert ca.crt -u "elastic:$ES_PASSWORD" -s https://localhost:9200/_cluster/health?pretty
curl --cacert ca.crt -u "elastic:$ES_PASSWORD" -s 'https://localhost:9200/_cat/indices?v&s=store.size:desc&h=index,pri,rep,docs.count,store.size' | head
curl --cacert ca.crt -u "elastic:$ES_PASSWORD" -s 'https://localhost:9200/_cat/shards?v&s=store:desc' | head
curl --cacert ca.crt -u "elastic:$ES_PASSWORD" -s 'https://localhost:9200/_cat/allocation?v'
curl --cacert ca.crt -u "elastic:$ES_PASSWORD" -s 'https://localhost:9200/_cluster/allocation/explain?pretty'      # pourquoi un shard n'est pas alloué

2. Mappings, templates and ILM #

Controlling the schema and the lifecycle.

Template and explicit mapping #

curl --cacert ca.crt -u "elastic:$ES_PASSWORD" -X PUT https://localhost:9200/_index_template/logs-app -H 'Content-Type: application/json' -d '{
  "index_patterns": ["logs-app-*"],
  "data_stream": {},
  "priority": 200,
  "template": {
    "settings": { "number_of_shards": 1, "number_of_replicas": 1, "index.lifecycle.name": "logs-30j", "index.codec": "best_compression" },
    "mappings": {
      "dynamic": "strict",
      "properties": {
        "@timestamp": { "type": "date" }, "level": { "type": "keyword" }, "message": { "type": "text" },
        "user_id": { "type": "keyword" }, "duration_ms": { "type": "long" }
      }
    }
  }
}'
Common mistake: An unrestricted dynamic mapping creates thousands of fields (mapping explosion). Use dynamic: strict and suitable types (keyword for filters, text for full text).
Good to know: The template has a priority of 200: without it, it overlaps the built-in logs-*-* template (priority 100) and the data stream may receive the built-in mapping instead of yours. Check the applied template with POST _index_template/_simulate_index/logs-app-default.

Lifecycle (ILM) #

curl --cacert ca.crt -u "elastic:$ES_PASSWORD" -X PUT https://localhost:9200/_ilm/policy/logs-30j -H 'Content-Type: application/json' -d '{
  "policy": { "phases": {
    "hot":    { "actions": { "rollover": { "max_primary_shard_size": "50gb", "max_age": "1d" } } },
    "warm":   { "min_age": "7d",  "actions": { "forcemerge": { "max_num_segments": 1 } } },
    "delete": { "min_age": "30d", "actions": { "delete": {} } }
  } }
}'
curl --cacert ca.crt -u "elastic:$ES_PASSWORD" -s https://localhost:9200/_ilm/status
curl --cacert ca.crt -u "elastic:$ES_PASSWORD" -s 'https://localhost:9200/logs-app-*/_ilm/explain?pretty' | head -30

3. Memory, security and backups #

Production stability.

JVM and system #

# jvm.options.d/heap.options : 50 % de la RAM maximum, jamais plus de ~30 Go
-Xms16g
-Xmx16g

sudo sysctl -w vm.max_map_count=262144
sudo swapoff -a                       # ou bootstrap.memory_lock: true
curl --cacert ca.crt -u "elastic:$ES_PASSWORD" -s 'https://localhost:9200/_nodes/stats/jvm?filter_path=**.heap_used_percent&pretty'

Security #

  • Enable TLS (transport and HTTP) and authentication; use API keys with limited scope.
  • Never expose port 9200 on the Internet; go through a reverse proxy.
  • One write role per ingestion pipeline, one read role per team.
curl --cacert ca.crt -u "elastic:$ES_PASSWORD" -X POST https://localhost:9200/_security/api_key -H 'Content-Type: application/json' -d '{
  "name": "ingestion-app",
  "role_descriptors": { "writer": { "indices": [{ "names": ["logs-app-*"], "privileges": ["create_doc", "auto_configure"] }] } },
  "expiration": "90d"
}'

Backups (snapshots) #

curl --cacert ca.crt -u "elastic:$ES_PASSWORD" -X PUT https://localhost:9200/_snapshot/depot -H 'Content-Type: application/json' -d '{ "type": "s3", "settings": { "bucket": "es-snapshots" } }'
curl --cacert ca.crt -u "elastic:$ES_PASSWORD" -X PUT https://localhost:9200/_slm/policy/quotidien -H 'Content-Type: application/json' -d '{
  "schedule": "0 30 1 * * ?", "name": "<snap-{now/d}>", "repository": "depot",
  "config": { "indices": ["logs-*"] }, "retention": { "expire_after": "30d", "min_count": 5 } }'
curl --cacert ca.crt -u "elastic:$ES_PASSWORD" -s https://localhost:9200/_snapshot/depot/_all?pretty | head -20
Good practice: Test restores regularly: a backup that has never been restored is not a backup.

4. Efficient queries and ingestion #

Bulk, filters and pagination.

Good habits #

# Ingestion : _bulk par lots de 5 à 15 Mo
curl --cacert ca.crt -u "elastic:$ES_PASSWORD" -s -H 'Content-Type: application/x-ndjson' -XPOST https://localhost:9200/_bulk --data-binary @lot.ndjson | jq '.errors'

# Filtres (cachés, sans score) plutôt que must pour les conditions exactes
curl --cacert ca.crt -u "elastic:$ES_PASSWORD" -s https://localhost:9200/logs-app-*/_search -H 'Content-Type: application/json' -d '{
  "size": 20, "_source": ["@timestamp","level","message"],
  "query": { "bool": { "filter": [ { "term": { "level": "error" } }, { "range": { "@timestamp": { "gte": "now-15m" } } } ] } },
  "sort": [{ "@timestamp": "desc" }]
}'
# Pagination profonde : search_after + PIT
curl --cacert ca.crt -u "elastic:$ES_PASSWORD" -s -XPOST 'https://localhost:9200/logs-app-*/_pit?keep_alive=1m'
AvoidPrefer
from: 100000search_after with PIT
Leading wildcard *textSuitable analyzer (n-gram) or dedicated field
Updating a document in a loopBulk reindexing, append-only model
One index per day without rolloverData streams and ILM

Reference diagram and quick check #

Visualize the principle and check it from the command line.

Reference diagram #

Elasticsearch ILM phases
Adjust durations to your business needs.
curl --cacert ca.crt -u "elastic:$ES_PASSWORD" -s 'https://localhost:9200/_cat/indices/logs-*?v&h=index,health,pri,store.size&s=index'

📄 Elasticsearch best practices: mappings, shards, lifecycle and operations →

My progress

  • ⏱ Estimated time : ≈ 12 min

Sign in to track your progress and take notes. Sign in

⭐ Rate this lesson

5.0 initial rating from the teaching team

Sign in to rate this lesson →

💬 Recent discussions about this course

Ask a question about this lesson →See all discussions about this course

Course Glossary

RBAC (Role-Based Access Control)

An access control method where permissions are assigned to specific roles (e.g., admin, reader) rather than directly to individual users.

Authentication

The process of verifying the identity of a user or system (e.g., login/password, tokens, biometrics).

Authorization

The process that occurs after authentication to determine if the entity has the necessary rights and privileges to access a resource.

API Key

A unique alphanumeric code used to identify, authenticate, and authorize access to an Application Programming Interface (API).

Architecture

The overall structural design of an IT system, defining its various components, their relationships, and the principles guiding its evolution.

Repository

A centralized storage location. This can refer to a source code repository (e.g., Git) or an artifact and binary repository (e.g., Harbor, Nexus, Arti...

Elasticsearch

A distributed, RESTful search and analytics engine capable of addressing a growing number of use cases, built on Apache Lucene.

Recommended Articles

Elasticsearch monitoring and troubleshooting: health, unassigned shards, JVM, hot threads and slow logs

Diagnose an Elasticsearch cluster: cluster health and CAT APIs, unassigned shards and allocation ...

Index Lifecycle Management (ILM): data tiers, rollover and retention

Automate the index lifecycle with ILM: hot, warm, cold and frozen data tiers, rollover by size an...

Elasticsearch data streams and templates: component templates, index templates and time series

Manage timestamped data with data streams: index templates and component templates, the type-data...

Elasticsearch performance and capacity planning: shards, heap, indexing and benchmarks

Size and optimize Elasticsearch: shard size and count, JVM heap, caches, indexing settings (refre...

Elasticsearch mappings and text analysis: field types, analyzers and dynamic mapping

Master Elasticsearch mappings: field types (text, keyword, numeric, date, ip, nested), multi-fiel...

Elasticsearch distributed architecture: node roles, shards, replicas and allocation

Understand how Elasticsearch works as a distributed system: node roles, master nodes and quorum, ...

Snapshot Lifecycle Management: automated backups, restore and disaster recovery

Protect Elasticsearch data: snapshot repositories (S3, GCS, Azure, file system), SLM policies wit...

Elasticsearch ingestion: Bulk API, ingest pipelines, enrich and reindex

Ingest and transform data in Elasticsearch: Bulk API, ingest pipelines and processors (grok, diss...

Advanced Elasticsearch security: TLS, certificates, API keys, FLS, DLS and audit

Secure Elasticsearch in depth: transport and HTTP TLS, certificate management with elasticsearch-...

Support us

♥ SUPPORT US

Support RousselTM Learning

Courses, articles, labs and certificates stay free with no intrusive ads. A voluntary contribution, of any amount you choose, pays for hosting, lab environments and new content.

Contribute with PayPal Any amount · card or PayPal accountLearn more
QR code PayPal
Or scan this QR code with your phone

Thank you, every contribution counts!