Skip to content
Tutorials Center
My learning

Topics

Lesson 43 of 43 ยท Practice and Review

Elasticsearch Cheat Sheet

A one-page Elasticsearch cheat sheet: REST calls, query DSL patterns, mapping types, aggregation recipes, plus health and troubleshooting commands.

This is the page to keep open while you work. It lists the REST calls, query patterns, mapping types, aggregation recipes and troubleshooting commands you need most, with a pointer to the lesson that explains each one. Everything in the code blocks is read-only: Elasticsearch does not run on this site, so you would paste these requests into Kibana Dev Tools or send them with curl against your own cluster.

Two small stand-ins at the end are runnable: a lookup over a request table and the cluster-health rule. They model the idea in JavaScript and are not the real engine. Example names such as products are placeholders, and exact options can differ between versions, so check the reference for your version when in doubt.

What is on this sheet

REST calls Create, read, search, bulk.
Query DSL Match, term, bool, range.
Mappings Field types and options.
Aggregations Metrics, buckets, dates.

Troubleshooting commands follow at the end.

1 / 2

REST basics

In Dev Tools you write METHOD /path and a JSON body. With curl, add the host, credentials and a content-type header. (Elasticsearch 8 and later enable security and TLS by default, so a local test cluster usually needs HTTPS and a password or API key. See Setup and Your First Requests.)

Terminal
curl --cacert http_ca.crt -u elastic:$ELASTIC_PASSWORD \
  -H "Content-Type: application/json" \
  -X GET "https://localhost:9200/products/_search" \
  -d '{ "query": { "match_all": {} } }'
Task Request
Cluster info GET /
Cluster health GET /_cluster/health
List indices GET /_cat/indices?v
Create index PUT /products
Delete index DELETE /products
Show mapping GET /products/_mapping
Show settings GET /products/_settings
Index with auto id POST /products/_doc
Index with your id PUT /products/_doc/1
Get by id GET /products/_doc/1
Partial update POST /products/_update/1
Delete document DELETE /products/_doc/1
Search GET /products/_search
Count GET /products/_count
Bulk POST /_bulk
Test an analyzer GET /_analyze
Refresh now POST /products/_refresh

A partial update wraps the changed fields in doc:

JSON
POST /products/_update/1
{ "doc": { "price": 79.0 } }

The bulk body is newline-delimited JSON (NDJSON): an action line, then a source line (none for delete). It must end with a newline.

JSON
POST /_bulk
{ "index":  { "_index": "products", "_id": "1" } }
{ "name": "Trail shoes", "price": 89 }
{ "update": { "_index": "products", "_id": "1" } }
{ "doc": { "price": 79 } }
{ "delete": { "_index": "products", "_id": "2" } }

More in Documents, Indexes and CRUD and Using Elasticsearch from Code.

Mapping types

Type Use for
text Full-text search, analyzed
keyword Exact values, filters, sorting, aggregations
long, integer, short, byte Whole numbers
double, float, scaled_float Decimals (scaled_float for fixed precision such as money)
boolean true or false
date Dates and timestamps
ip IPv4 and IPv6 addresses
geo_point Latitude and longitude
object Nested JSON, flattened into dotted fields
nested Array of objects that must stay paired
flattened Whole object as keyword values, for unpredictable keys
dense_vector Embeddings for kNN search
search_as_you_type Prefix and infix autocomplete
JSON
PUT /products
{
  "settings": { "number_of_shards": 1, "number_of_replicas": 1 },
  "mappings": {
    "dynamic": "strict",
    "properties": {
      "name":  { "type": "text", "fields": { "raw": { "type": "keyword" } } },
      "brand": { "type": "keyword" },
      "price": { "type": "scaled_float", "scaling_factor": 100 },
      "added": { "type": "date" }
    }
  }
}

Fields cannot change type in place: create a new index and reindex. Details: Mappings and Field Types, Dynamic Mapping and Index Templates.

Query DSL patterns

Need Query
Everything { "match_all": {} }
Full text { "match": { "name": "running shoes" } }
All words { "match": { "name": { "query": "running shoes", "operator": "and" } } }
Phrase { "match_phrase": { "name": "running shoes" } }
Several fields { "multi_match": { "query": "nova", "fields": ["name^2", "brand"] } }
Typos { "match": { "name": { "query": "runing", "fuzziness": "AUTO" } } }
Exact value { "term": { "brand": "Nova" } }
Several values { "terms": { "brand": ["Nova", "Terra"] } }
Range { "range": { "price": { "gte": 10, "lt": 100 } } }
Field exists { "exists": { "field": "price" } }
By ids { "ids": { "values": ["1", "2"] } }

Combine them with bool: must and should score, filter and must_not do not.

JSON
GET /products/_search
{
  "query": {
    "bool": {
      "must":     [ { "match": { "name": "running" } } ],
      "filter":   [ { "term": { "brand": "Nova" } },
                    { "range": { "price": { "lte": 100 } } } ],
      "should":   [ { "term": { "in_stock": true } } ],
      "must_not": [ { "term": { "discontinued": true } } ]
    }
  },
  "sort": [ { "price": "asc" }, "_score" ],
  "from": 0,
  "size": 10,
  "_source": ["name", "price"],
  "highlight": { "fields": { "name": {} } }
}

Use term on keyword, numbers and dates, and match on text. See Query DSL Basics, Full-Text Queries and Bool Queries and Compound Logic.

Pagination

JSON
GET /products/_search
{ "size": 100, "sort": [ { "price": "asc" }, { "_id": "asc" } ], "search_after": [89.0, "17"] }

from + size is limited by index.max_result_window (10,000 by default). For deep paging, open a point in time with POST /products/_pit?keep_alive=1m, pass its id in the search and continue with search_after (Sorting and Pagination).

Aggregation recipes

Add "size": 0 to get only the aggregation results.

JSON
GET /orders/_search
{
  "size": 0,
  "aggs": {
    "avg_amount":  { "avg": { "field": "amount" } },
    "amount_stats": { "stats": { "field": "amount" } },
    "unique_users": { "cardinality": { "field": "user_id" } },
    "by_country": {
      "terms": { "field": "country", "size": 10 },
      "aggs": { "revenue": { "sum": { "field": "amount" } } }
    },
    "per_day": {
      "date_histogram": { "field": "ordered_at", "calendar_interval": "day" }
    },
    "price_bands": {
      "range": { "field": "amount", "ranges": [ { "to": 50 }, { "from": 50, "to": 200 }, { "from": 200 } ] }
    }
  }
}

cardinality is approximate. terms counts can be approximate across shards (see doc_count_error_upper_bound in the response). For paging through all buckets use a composite aggregation. For filtered facets use post_filter. More: Aggregations: Metrics and Buckets, Sub-Aggregations and Pipeline Aggregations, Faceted Search and Filters.

Analysis

JSON
GET /_analyze
{ "analyzer": "standard", "text": "The Quick-Brown Fox" }

The result lists the tokens. To test an analyzer of a specific index, call GET /products/_analyze with "field": "name". See Analysis, Tokenizers and Analyzers.

Aliases and reindexing

JSON
POST /_reindex
{ "source": { "index": "products-v1" }, "dest": { "index": "products-v2" } }

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

Both alias actions run atomically, so clients that use the alias products switch to the new index with no downtime.

Health and troubleshooting

Question Command
Is the cluster up? What color? GET /_cluster/health
Which indices are yellow or red? GET /_cluster/health?level=indices
Shard list and states GET /_cat/shards?v
Why is a shard unassigned? GET /_cluster/allocation/explain
Node list and load GET /_cat/nodes?v
Disk usage per node GET /_cat/allocation?v
Index sizes and doc counts GET /_cat/indices?v&s=store.size:desc
Why this score? GET /products/_explain/1 with a query body
Why is a query slow? Add "profile": true to the search body
Pending cluster tasks GET /_cluster/pending_tasks
Task list GET /_tasks?detailed
Color Meaning Typical cause
Green All primaries and replicas allocated Healthy
Yellow All primaries allocated, some replicas not Single node, or a node is down
Red At least one primary unassigned Lost node, full disk, corrupted shard

Common problems and first checks:

  • Full disk: when a disk crosses its high watermark, Elasticsearch stops allocating shards to it, and at the flood-stage watermark it makes indices read-only. Free space first, then clear the block as your version's documentation describes.
  • Mapping errors on index (400): a value does not fit the field type. Read the error, fix the data or the mapping, and reindex if the mapping must change.
  • Search returns nothing: check analysis (_analyze), term vs match, and whether the document has been refreshed yet.
  • Too many shards: list them with _cat/shards, then merge small indices or use rollover and ILM.

For performance tips, see Query Performance and Tuning, and for users, API keys and snapshots, Security, Backups and Operations.

Two runnable stand-ins

The first stand-in is a searchable version of the request table. The second applies the health color rule. Neither talks to a real cluster.

JS Look up a request from the sheet

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The word delete finds nothing because the small table has no delete row, a reminder that a cheat sheet is only as complete as its author made it.

JS The health color rule

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The real cluster health also considers details such as initializing shards and the cluster's own state, but the three colors follow this core rule.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which bool clause adds to the relevance score?

    must and should contribute to the score. filter and must_not only include or exclude documents.
  2. 2. A cluster with one node and replicas set to 1 is most likely which color?

    The replica cannot be allocated on the same node as its primary, so primaries are fine but replicas are unassigned: yellow.
  3. 3. Which request explains why a shard is unassigned?

    The allocation explain API reports the reasons a shard cannot be allocated, node by node.
  4. 4. How do you switch clients from products-v1 to products-v2 without downtime?

    Alias actions in one request are applied atomically, so clients using the alias see the new index immediately.

Summary

  • REST: PUT creates, POST adds or updates, GET reads and searches, DELETE removes. Bulk bodies are NDJSON.
  • text is for searching and keyword for exact values; mappings cannot change in place.
  • Put scoring clauses in must and should, exact conditions in filter and must_not.
  • Use size: 0 with aggs, search_after for deep paging, and aliases for zero-downtime reindexing.
  • Troubleshoot with _cluster/health, _cat/shards, _cluster/allocation/explain, _analyze, _explain and profile.

This is the last lesson of the track. Go back to What Is Elasticsearch? to review from the beginning, or try the Project: Build a Mini Search Engine again with your own extensions.