Reputation: 33
I have documents like below indexed,
1.
{
"name": "Gilly",
"hobbyName" : "coin collection",
"countries": ["US","France","Georgia"]
}
2.
{
"name": "Billy",
"hobbyName":"coin collection",
"countries":["UK","Ghana","China","France"]
}
Now I need to sort these documents based on the array length of the field "countries", such that the result after the sorting would be of the order document2,document1. How can I achieve this using elasticsearch?
Upvotes: 3
Views: 3144
Reputation: 19253
I would suggest using token count type in Elasticsearch. By using scripts , it can be done (can check here for how to do it using scripts). But then results wont be perfect. Scripts mostly uses filed data cache and duplicate are removed in this.
You can read more on how to use token count type here.
Upvotes: 2
Reputation: 6357
You can use script based sorting to achieve this.
{
"query": {
"match_all": {}
},
"sort": {
"_script": {
"type": "number",
"script": "doc['countries'].values.size()",
"order": "desc"
}
}
}
Upvotes: 3