Search and Elasticsearch learning path Level 4 This level · 5 of 8
Hard search elasticsearch

What makes sorting expensive in Elasticsearch, and how can index sorting help?

The 30 second answer

Sorting reads each matching document's value from doc values, a columnar on-disk structure, and keeps the best N per shard. It breaks on text fields, which have no doc values by default; enabling fielddata loads them into heap, which is costly. Sort on keyword or numeric fields instead. If one sort dominates, like newest first, index sorting stores documents in that order, so with track_total_hits false a shard can stop early.

Could you say this in an interview?

How sorting works. The inverted index answers "which documents contain this term?". Sorting needs the opposite: "what is the price of document 42?". That's what doc values are: the docs describe them as the same values as _source "but in a columnar format that is more efficient for sorting and aggregation". They're on by default for keyword, numeric, date, boolean and similar fields, and not enabled by default for text fields.

Sorting on text. Sorting or aggregating on a text field fails with an error that fielddata is disabled. Setting fielddata: true loads the analyzed terms into heap; the docs warn it "can consume significant memory", that calculating it "can cause latency spikes", and that it "usually doesn't make sense". Sort on a keyword sub-field instead, perhaps with a normalizer for case.

Badly written.

PUT products/_mapping
{ "properties": { "name": { "type": "text", "fielddata": true } } }

GET products/_search
{ "sort": [ { "name": "asc" } ], "query": { "match_all": {} } }

Better.

PUT products
{ "mappings": { "properties": {
    "name": { "type": "text",
              "fields": { "sort": { "type": "keyword", "normalizer": "lowercase" } } } } } }

GET products/_search
{ "sort": [ { "name.sort": "asc" }, { "sku": "asc" } ] }

(The lowercase normalizer has to be defined in the index settings.)

Index sorting. By default, the docs say, "a search request must visit every document that matches a query to retrieve the top documents sorted by a specified sort". If the index is stored sorted the same way as the query, for example created_at desc for a "newest first" feed, each segment can stop after the first N matches, provided you set track_total_hits: false:

PUT new_arrivals
{ "settings": { "index": { "sort.field": "created_at", "sort.order": "desc" } } }

GET new_arrivals/_search
{ "size": 48, "sort": [ { "created_at": "desc" } ], "track_total_hits": false }

Index sorting "can be defined only once at index creation" and "has a cost in terms of indexing throughput since documents must be sorted at flush and merge time". The docs also show that sorting on fields often used together in filters can speed up conjunctions.

Trade-offs.

  • Sorting by score is usually cheapest for relevance queries, because Lucene can skip documents that can't make the top N.
  • Every extra sort key reads another doc-values column.
  • Index sorting pays off only for one dominant sort order; it doesn't help other orders.

Alternate interview scenarios

"Sort by price must use the price in the shopper's market."

Store one numeric price per market (price_de, price_fr) or one index per market, and sort on that field. Computing it in a script per document is the slow path the slow-query page warns about.

"Sort by distance to the nearest store."

_geo_distance sort computes a distance per matching document. Filter by a radius first so fewer documents are sorted (see the range and geo question).

Sources (5)
  1. Elasticsearch docs: doc_valueselastic.co
  2. Elasticsearch docs: Text field type (fielddata)elastic.co
  3. Elasticsearch docs: Index sorting settings (early termination)elastic.co
  4. Elasticsearch docs: Use index sorting to speed up conjunctionselastic.co
  5. Elasticsearch docs: Sort search resultselastic.co
Previous
Next