You can do this by indexing an additional field that contains the number of tags on which you can easily sort the results. Otherwise, if you are willing to pay a small execution cost during the request, there is a good solution that does not require reindexing your data: you can sort based on the script as follows:
{ "query" : { "match_all" : {} }, "sort" : { "_script" : { "script" : "doc['tags'].values.length", "type" : "number", "order" : "asc" } } }
As you can read the script based sorting section:
Note. It is recommended for a separate script-based sort based on user preferences, use the custom_score query instead, since evaluation sorting is faster.
This means that it would be better to use a custom counting query to affect your score and then sort by the result, for example:
{ "query" : { "custom_score" : { "query" : { "match_all" : {} }, "script" : "_score * doc['tags'].values.length" } } }
source share