Skip to content

Tune Elasticsearch search queries

Tune slow Elasticsearch search queries by finding the expensive clauses and changing how the query is written. You will profile a query, move yes/no conditions into cached filters, trim returned fields, and page deep results with search_after.

If you run Elasticsearch in production and some searches take seconds, the way the query is written is often what slows it down. Common culprits are yes/no conditions placed where Elasticsearch computes relevance scores, responses that return whole documents, and deep pages fetched with from and size. The fixes below start with the profile API, which shows how long each part of a query takes. Then you move filters into filter context, where results are cached and no score is computed. You also return only the fields you need and switch deep pagination to search_after, a cursor that stays fast at any depth. Together these changes can bring p95 latency (the time within which 95% of searches finish) from seconds down to milliseconds.

How to verify

Find the slow queries before changing them:

curl -sk -u elastic:"$PW" 'https://es:9200/_nodes/stats/indices/search?pretty' | jq '.nodes | to_entries | map({node: .key, query_total: .value.indices.search.query_total, query_time_in_millis: .value.indices.search.query_time_in_millis}) | .[]'
curl -sk -u elastic:"$PW" 'https://es:9200/products/_settings?include_defaults=true&filter_path=**.search.slowlog*'
curl -sk -u elastic:"$PW" -X POST 'https://es:9200/products/_search' -H 'Content-Type: application/json' \
  -d '{"profile": true, "query": {"match": {"name": "linen"}}}'
journalctl -u elasticsearch -n 200 --no-pager | grep -i slowlog

Enable the slow log on the hot index:

curl -sk -u elastic:"$PW" -X PUT 'https://es:9200/products/_settings' \
  -H 'Content-Type: application/json' \
  -d '{"index.search.slowlog.threshold.query.warn": "1s", "index.search.slowlog.threshold.query.info": "500ms"}'

What’s happening

Elasticsearch breaks queries into two contexts:

  • Query context computes BM25 relevance scores. Slower, but the only way to rank by relevance.
  • Filter context answers “does this match yes/no?” — no scoring, results are cached in the filter cache.

Most queries mix the two: a few filters (date range, status=active) plus one or two scoring matches. Putting filters in filter instead of must is a 3-10x speedup with zero correctness change.

Other levers:

  • Source filtering (_source: ["a", "b"]) reduces document size returned over the wire and parsed by the client.
  • Runtime fields let you compute values at query time without re-indexing — but they’re CPU-bound on every query, so pre-index frequently-filtered fields.
  • search_after for deep pagination — from: 10000, size: 10 materializes 10010 docs across the cluster; search_after uses a cursor and stays O(size).
  • Stored vs _source — _source (the original JSON) is the default. Setting store: true on individual fields lets you fetch them without parsing the full source — useful for very large documents.

The query profile API tells you which clauses cost what — read it before guessing.

The procedure

1. Profile the slow query:

curl -sk -u elastic:"$PW" -X POST 'https://es:9200/products/_search?pretty' \
  -H 'Content-Type: application/json' \
  -d '{
    "profile": true,
    "size": 10,
    "_source": ["name", "price"],
    "query": {
      "bool": {
        "must": [{"match": {"name": "linen shirt apex"}}],
        "filter": [
          {"term": {"in_stock": true}},
          {"range": {"price": {"gte": 20, "lte": 200}}}
        ]
      }
    }
  }'

In the response, look at profile.shards[*].searches[*].query[*].breakdown.next_doc and score. High values point at expensive sub-queries.

2. Move scoring filters to filter context. Anti-pattern:

{"bool": {"must": [
  {"match": {"name": "linen"}},
  {"term": {"in_stock": true}},
  {"range": {"price": {"gte": 20}}}
]}}

Better:

{"bool": {
  "must":   [{"match": {"name": "linen"}}],
  "filter": [
    {"term": {"in_stock": true}},
    {"range": {"price": {"gte": 20}}}
  ]
}}

Filters are cached. Reuse across queries hits the cache.

3. Reduce returned source:

curl -sk -u elastic:"$PW" -X POST 'https://es:9200/products/_search?pretty' \
  -H 'Content-Type: application/json' \
  -d '{
    "_source": ["id", "name", "price"],
    "size": 20,
    "query": {"match_all": {}}
  }'

For huge documents (full HTML, embeddings) the wire saving is dramatic. Pair with fields if you also need runtime-computed values.

4. Replace deep pagination with search_after:

curl -sk -u elastic:"$PW" -X POST 'https://es:9200/products/_search?pretty' \
  -H 'Content-Type: application/json' \
  -d '{
    "size": 20,
    "sort": [{"price": "asc"}, {"id": "asc"}],
    "query": {"match_all": {}}
  }'

The last hit returns sort: [29.0, "abc123"]. Next page:

curl -sk -u elastic:"$PW" -X POST 'https://es:9200/products/_search?pretty' \
  -H 'Content-Type: application/json' \
  -d '{
    "size": 20,
    "sort": [{"price": "asc"}, {"id": "asc"}],
    "search_after": [29.0, "abc123"],
    "query": {"match_all": {}}
  }'

max_result_window (default 10000) caps from+size. search_after has no such cap.

5. Pre-aggregate or use field collapsing when you only need one hit per group:

{
  "query": {"match": {"name": "shirt"}},
  "collapse": {"field": "brand.keyword"}
}

Returns one document per brand — cheaper than computing top_hits in an aggregation.

6. Cap aggregations. A terms aggregation defaults to size: 10 but can blow up with size: 0 on high-cardinality fields:

{
  "size": 0,
  "aggs": {
    "by_brand": {
      "terms": {"field": "brand.keyword", "size": 20, "execution_hint": "map"}
    }
  }
}

execution_hint: "map" works well for low-cardinality fields. Set shard_size higher than size for accuracy across shards.

Common pitfalls

  • wildcard queries with leading wildcard. *linen is a full-index scan. Use a keyword field with prefix query, or index reversed copies for trailing wildcards.
  • query_string query in user input. It accepts Lucene syntax — a stray : from the user breaks parsing. Use simple_query_string or match.
  • Forgetting track_total_hits: false when you don’t need exact totals. Setting false (or a small number) returns the cap quickly.
  • script queries. Every match evaluates a script. Convert to runtime_fields only if the field is queried rarely; otherwise pre-index.
  • refresh=wait_for on every write — kills indexing throughput. Use only when read-your-writes consistency matters.
  • High-cardinality terms agg without size — defaults to 10, can miss the brand you care about. Set size explicitly.

In the engagements we run, tuning queries is mostly about reading the profile output, not guessing. The wins are usually in three places: filter/must split, source filtering, and replacing deep pagination. Once the queries are clean, shard sizing and ILM tier health become the dominant factors. See /en/services/managed-operations/ for how we operate search at low latency under production traffic.