Skip to main content

Sorting

sort is an array of Elasticsearch sort clauses. It has three jobs, depending on the request:

RequestWhat sort does
Document list (no aggs)Orders the documents
Aggregation with groupsOrders the groups whose field appears in sort
Composite modeOrders the groups and the documents inside each group (top_hits)

Clauses​

sort: [
{ total: 'desc' }, // number
{ orderedAt: 'asc' }, // date
{ 'status.keyword': 'asc' } // text: use the .keyword form
]

The field to sort by is the same as for exact matches (see field names): field.keyword for text, the plain field for numbers, dates and booleans. Sorting on a text field without .keyword fails.

From the Insights app's sort model [{ field: 'status', sort: 'asc' }] you get:

{ [def.sortField ?? keywordField(def)]: 'asc' } // 'status.keyword' for text, 'total' for numbers

The helper buildSort in From a chart to code does exactly this. Fields that do not exist in the source are skipped.

Default order​

With an empty sort, documents come back in index order (_doc). That is stable, which makes it suitable for paging, but not meaningful. Always sort explicitly if the order matters, and add a unique tie-breaker so that pages do not repeat or skip rows:

sort: [{ orderedAt: 'desc' }, { 'orderId.keyword': 'asc' }]

Sorting groups​

In an aggregation-mode request, a group is ordered by its own key if sort contains an entry for the group's field:

{
aggMode: 'aggregation',
sort: [{ 'category.keyword': 'asc' }],
aggs: [{ id: 'cat', field: 'category.keyword', aggregation: 'terms', options: { size: 10 } }]
}
  • Without such an entry, terms groups are ordered by document count, descending. With options.size: 10 you get the top 10.
  • With an entry, groups are ordered by key, so size: 10 returns the first 10 keys, not the biggest ones.
  • Date interval groups (datetime-interval) are always in time order.
  • filters and geo-region groups are ordered by options.sortOrder (a map of label to position), otherwise alphabetically.

Sorting by a metric​

Sorting groups by a metric or by count is not supported by the API. The Insights app sorts metric columns in the browser. Do the same:

const rows = result.rows
.filter(row => row.aggregation.depth === 1)
.map(row => row.aggregation.fields)
.sort((a, b) => b.revenue - a.revenue)
.slice(0, 5) // top 5 by revenue

Because the API returns groups by count by default, ask for more groups than you need (a high options.size), then sort and trim in code. To find the top N by a metric reliably, request all groups (up to the size limits).

Composite mode​

In composite mode sort orders the composite keys (groups) that appear in it, and is also used to order the documents inside each group. See Modes and paging.