Sort based on length of an array in elasticsearch Sort based on length of an array in elasticsearch elasticsearch elasticsearch

Sort based on length of an array in elasticsearch


There are two options here.

  1. Use token count type as multi field in the mapping - This way another field would be stored as mutlti field which has the length of the array . You can learn more about it here.
  2. Scripting - The same can be achieved using scripting too .

    { "sort": { "_script": { "script": "doc['countryCodes'].values.size()" } } }


For Elasticsearch 5.6.7 query should look like this:

GET index/_search{    "query": {        "match_all": {}    },    "sort": {        "_script": {            "type" : "number",            "script" : {                "lang": "painless",                "source": "doc.countryCodes.values.size()"            },            "order" : "desc"        }    }}


The easiest way to do this would be to also index another field containing the length of the array and then sort on that field.

Another way would be to use script-based sorting and return the length of the array using groovy.

{  "query": {    "match_all": {}  },  "sort": {    "_script": {      "script": "doc.countryCodes.values.size()"    }  }}

Also make sure to enable dynamic scripting in order for this to work.