0
0
Elasticsearchquery~5 mins

Sorting results in Elasticsearch

Choose your learning style9 modes available
Introduction

Sorting results helps you see data in the order you want, like from highest to lowest or alphabetically.

When you want to show the newest items first in a list.
When you need to find the cheapest products in a store.
When you want to organize search results by name or date.
When you want to rank items by popularity or rating.
Syntax
Elasticsearch
{
  "sort": [
    { "field_name": { "order": "asc" } }
  ]
}

Use asc for ascending order (smallest to largest or A to Z).

Use desc for descending order (largest to smallest or Z to A).

Examples
This sorts results by the price field from lowest to highest.
Elasticsearch
{
  "sort": [
    { "price": { "order": "asc" } }
  ]
}
This sorts results by the date field from newest to oldest.
Elasticsearch
{
  "sort": [
    { "date": { "order": "desc" } }
  ]
}
This sorts results alphabetically by the name field.
Elasticsearch
{
  "sort": [
    { "name.keyword": { "order": "asc" } }
  ]
}
Sample Program

This query finds all documents and sorts them by the age field from highest to lowest.

Elasticsearch
{
  "query": {
    "match_all": {}
  },
  "sort": [
    { "age": { "order": "desc" } }
  ]
}
OutputSuccess
Important Notes

If the field you sort by is text, use the keyword version (like name.keyword) to sort alphabetically.

You can sort by multiple fields by adding more objects inside the sort array.

Summary

Sorting arranges your search results in the order you want.

Use asc for ascending and desc for descending order.

You can sort by numbers, dates, or keywords for text fields.