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.
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.
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.
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.
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" ]
There are two options here.
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"
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With