Search code examples
sortingelasticsearch

How to alphabetically sort a name field in Elasticsearch?


I have the following definition for the name field:

"name": {
  "type": "text",
  "fields": {
    "keyword": {
      "type": "keyword",
      "ignore_above": 256
    }
  }
},

How do I sort this alphabetically ?

I am trying the following

{
  "query": {
    "match": {
      "name": "Shoes"
    }
  },
  "sort": {
    "keyword": {
       "order": "asc"
    }  
  },
  "size": 10,
  "from": 0,
  "sort": []
}

But the sort somehow doesn't seem to be doing anything at all.

I have referred to these threads but they doesn't seem to help in my case.

Thread 1

Thread 2


Solution

  • You need to refer to the name.keyword subfield and also you have two different sort sections in your search, remove the empty one:

    {
      "query": {
        "match": {
          "name": "Shoes"
        }
      },
      "sort": {
        "name.keyword": {         <---- change this
           "order": "asc"
        }  
      },
      "size": 10,
      "from": 0,
      "sort": []                  <---- remove this
    }