﻿---
title: Index sorting settings
description: When creating a new index in Elasticsearch it is possible to configure how the segments inside each shard will be sorted. By default Lucene does not apply...
url: https://www.elastic.co/elastic/docs-builder/docs/5066/reference/elasticsearch/index-settings/sorting
products:
  - Elasticsearch
applies_to:
  - Elastic Cloud Serverless: Generally available
  - Elastic Stack: Generally available
---

# Index sorting settings
When creating a new index in Elasticsearch it is possible to configure how the segments inside each shard will be sorted. By default Lucene does not apply any sort. The `index.sort.*` settings define which fields should be used to sort the documents inside each Segment.
<warning>
  It is allowed to apply index sorting to mappings with nested objects, so long as the `index.sort.*` setting contains no nested fields.
</warning>

For instance the following example shows how to define a sort on a single field:
```console
PUT my-index-000001
{
  "settings": {
    "index": {
      "sort.field": "date", <1>
      "sort.order": "desc"  <2>
    }
  },
  "mappings": {
    "properties": {
      "date": {
        "type": "date"
      }
    }
  }
}
```

It is also possible to sort the index by more than one field:
```console
PUT my-index-000001
{
  "settings": {
    "index": {
      "sort.field": [ "username", "date" ], <1>
      "sort.order": [ "asc", "desc" ]       <2>
    }
  },
  "mappings": {
    "properties": {
      "username": {
        "type": "keyword",
        "doc_values": true
      },
      "date": {
        "type": "date"
      }
    }
  }
}
```

<applies-to>Elastic Stack: Planned</applies-to> Instead of the separate `index.sort.*` settings, you can configure the whole sort with the single `index.sort` expression:
```console
PUT my-index-000001
{
  "settings": {
    "index": {
      "sort": "username, MV_MAX(date) DESC NULLS LAST" <1>
    }
  },
  "mappings": {
    "properties": {
      "username": {
        "type": "keyword",
        "doc_values": true
      },
      "date": {
        "type": "date"
      }
    }
  }
}
```

A sort key can also be computed by an ES|QL expression. For example, to group the documents of each hour, newest hour first, and sort them by host within each hour:
```console
PUT my-index-000001
{
  "settings": {
    "index": {
      "sort": "DATE_TRUNC(1 hour, @timestamp) DESC, host.name" <1>
    }
  },
  "mappings": {
    "properties": {
      "@timestamp": {
        "type": "date"
      },
      "host.name": {
        "type": "keyword"
      }
    }
  }
}
```

Index sorting supports the following settings:
<definitions>
  <definition term="">
    A comma-separated list of sort keys that configures the whole index sort, using the [ES|QL `SORT` syntax](https://www.elastic.co/elastic/docs-builder/docs/5066/reference/query-languages/esql/commands/sort). Each entry is a key, optionally followed by a sort order and the placement of documents without a value:
    - `field`, `MV_MIN(field)` or `MV_MAX(field)`: The field to sort by. For a multi-valued field, `MV_MIN` and `MV_MAX` sort by its lowest or highest value. Defaults to `MV_MIN` when ascending and `MV_MAX` when descending.
    - Any other ES|QL expression, for example `DATE_TRUNC(1 hour, @timestamp)`: A key computed from the doc values of the fields it reads. It is never stored. See [Computed sort keys](#index-sort-computed-keys) for the expressions it can use.
    - `ASC` or `DESC`: The sort order. Defaults to `ASC`.
    - `NULLS FIRST` or `NULLS LAST`: Where documents without a value are sorted. Like in ES|QL, a missing value counts as larger than any value, so this defaults to `NULLS LAST` for `ASC` and `NULLS FIRST` for `DESC`.
    Keywords and function names are case-insensitive. Unquoted field names follow the ES|QL identifier rules: dot-separated parts that start with a letter, `_` or `@` and contain only letters, digits and `_`, and that aren't a reserved word such as `null` or `asc`. Any other field name, for example one with a hyphen, whitespace or a comma, must be quoted with backticks, doubling any backtick in the name.
    The `NULLS` default for `DESC` differs from `index.sort.missing`, which defaults to `_last` for either order. It matches what an ES|QL `SORT field DESC` asks for, so the index sort and the query agree. To keep documents without a value last, write `NULLS LAST`.
    `index.sort` is parsed by ES|QL, so it needs the ES|QL plugin, which the default distribution includes. The `index.sort.*` settings don't.
    The expression is stored as written, and the index is sorted from it directly. The `index.sort.*` settings stay unset and default to empty, not to the index mode defaults or the values from the expression. `index.sort` can't be combined with any of the `index.sort.*` settings.
  </definition>
  <definition term="">
    The list of fields used to sort the index. Only `boolean`, `numeric`, `date` and `keyword` fields with `doc_values` are allowed here.
  </definition>
  <definition term="">
    The sort order to use for each field. The order option can have the following values:
    - `asc`:  For ascending order.
    - `desc`: For descending order.
    When `index.sort.field` is set but `index.sort.order` is not explicitly provided, each field defaults to `asc`.
  </definition>
  <definition term="">
    Elasticsearch supports sorting by multi-valued fields. The mode option controls what value is picked to sort the document. The mode option can have the following values:
    - `min`: 	Pick the lowest value.
    - `max`: 	Pick the highest value.
    When `index.sort.order` is set to `asc`, `index.sort.mode` defaults to `min`. If you set the order to `desc`, the mode defaults to `max`.
  </definition>
  <definition term="">
    The missing parameter specifies how docs which are missing the field should be treated. The missing value can have the following values:
    - `_last`: Documents without value for the field are sorted last.
    - `_first`: Documents without value for the field are sorted first.
    Documents missing the sort field are always sorted last by default, regardless of sort order.
  </definition>
</definitions>

<warning>
  Index sorting can be defined only once at index creation. It is not allowed to add or update a sort on an existing index. Index sorting also has a cost in terms of indexing throughput since documents must be sorted at flush and merge time. You should test the impact on your application before activating this feature.
</warning>


## Computed sort keys

<applies-to>
  - Elastic Stack: Planned
</applies-to>

A key of `index.sort` that isn't a field, `MV_MIN(field)` or `MV_MAX(field)` is computed by an ES|QL expression from the doc values of the fields it reads. The key is never stored: it's computed again each time a segment is sorted, when it's written and each time it's merged, on whichever node does it. An expression that breaks one of the following rules is rejected when the index is created.
<definitions>
  <definition term="Functions">
    A key can only use functions that always compute the same result for the same input, on every node and in every version, because a segment sorted by one node can be merged by another. These are the arithmetic, comparison and logical operators, `IS NULL`, `IS NOT NULL`, and the functions `CASE`, `COALESCE`, `DATE_TRUNC`, `MV_MIN` and `MV_MAX`.
    Other functions are rejected, for example functions whose floating point results may differ between JVMs, such as `SIN` and `ROUND`, functions that depend on the JVM's Unicode or locale data, such as `TO_LOWER`, and the type conversions, which parse strings. Aggregate and full-text functions are rejected too, because they don't compute a value for each document.
  </definition>
  <definition term="Fields">
    A key must read at least one field. Each field must have doc values and be of a numeric, `date`, `date_nanos`, `boolean`, `keyword`, `ip` or `version` type. It can't be an alias, a runtime field or a field under a `nested` object.
  </definition>
  <definition term="Result">
    A key must return a `long`, `integer`, `double`, `boolean`, `date` or `date_nanos` value. Documents for which it returns no value or several values sort like documents without a value, see `NULLS FIRST` and `NULLS LAST` in [`index.sort`](#index-sort-expression). Keys aren't rewritten by the ES|QL query optimizer, so on edge cases such as an overflow, a key can differ from the same expression in a query: `-n > 0` has no value when `-n` overflows, while a query rewrites it to `n < 0`, which is `true`.
  </definition>
</definitions>


## Early termination of search request

By default in Elasticsearch a search request must visit every document that matches a query to retrieve the top documents sorted by a specified sort. Though when the index sort and the search sort are the same it is possible to limit the number of documents that should be visited per segment to retrieve the N top ranked documents globally. For example, let’s say we have an index that contains events sorted by a timestamp field:
```console
PUT events
{
  "settings": {
    "index": {
      "sort.field": "timestamp",
      "sort.order": "desc" <1>
    }
  },
  "mappings": {
    "properties": {
      "timestamp": {
        "type": "date"
      }
    }
  }
}
```

You can search for the last 10 events with:
```console
GET /events/_search
{
  "size": 10,
  "sort": [
    { "timestamp": "desc" }
  ]
}
```

Elasticsearch will detect that the top docs of each segment are already sorted in the index and will only compare the first N documents per segment. The rest of the documents matching the query are collected to count the total number of results and to build aggregations.
If you’re only looking for the last 10 events and have no interest in the total number of documents that match the query you can set `track_total_hits` to false:
```console
GET /events/_search
{
  "size": 10,
  "sort": [ <1>
      { "timestamp": "desc" }
  ],
  "track_total_hits": false
}
```

This time, Elasticsearch will not try to count the number of documents and will be able to terminate the query as soon as N documents have been collected per segment.
```json
{
  "_shards": ...
   "hits" : {  
      "max_score" : null,
      "hits" : []
  },
  "took": 20,
  "timed_out": false
}
```

<note>
  Aggregations will collect all documents that match the query regardless of the value of `track_total_hits`
</note>