Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort based on length of an array in elasticsearch

There is a field where there is an array stored. I want to sort the documents based on the array length of that field.

Sample documents

document 1 = {
"countryCodes" : ["US","UK","UA","IN"]
}

document 2 ={
"countryCodes" : ["FR","SU","UG","UK","US"]
}

So, up on sort, the results should be showing document 2 first and then document 1.

like image 332
michael lother Avatar asked Nov 27 '15 12:11

michael lother


People also ask

How do you sort an array by size?

To sort strings in an array based on length in JavaScript, call sort() method on this string array and pass a comparison function to sort() method, such that the comparison happens for the length of elements.

What is the default sort order in Elasticsearch?

In Elasticsearch, the relevance score is represented by the floating-point number returned in the search results as the _score , so the default sort order is _score descending.

How do you sort in elastic?

You can sort Elasticsearch results using the sort keyword. The sort query requires you to provide a field under which to sort. Elasticsearch does not support sorting on fields of type text. In this short guide, we will look at how to sort query results in Elasticsearch.

What data stores an array Elasticsearch?

In Elasticsearch, there is no dedicated array data type. Any field can contain zero or more values by default, however, all values in the array must be of the same data type. For instance: an array of strings: [ "one" , "two" ]


2 Answers

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()" } } }

like image 58
Vineeth Mohan Avatar answered Sep 29 '22 10:09

Vineeth Mohan


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"
        }
    }
}
like image 23
Luka Lopusina Avatar answered Sep 29 '22 10:09

Luka Lopusina