How to sort search results according to the number of elements in ElasticSearch?

Let's say that I am storing documents like this in ElasticSearch:

{ 'name':'user name', 'age':43, 'location':'CA, USA', 'bio':'into java, scala, python ..etc.', 'tags':['java','scala','python','django','lift'] } 

And let's say what I'm looking for using location = CA, how can I sort the results according to the number of elements in the 'tags'?

I would like to list the people with the most tags on the first page.

+2
source share
1 answer

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" } } } 
+3
source

All Articles