Modify sort mechanism of elasticsearch by counting matched elements in array properties


I am trying to achieve a "Best Match" strategy for the results in my platform that uses Elasticsearch 7.15.

Basically, there are the rules on how it should work:

Every property that you match with a query_string (and it must always be a query string to support operators such as AND, OR), you will receive 1 score point boost.

So let's say I have the following properties:


(this is just an example).

And I have 3 results in the database:

  1. {cars: ['ben'], houses: ['ben'], ships: ['tal']}

  2. {cars: ['ben'], houses: ['], ships: ['tal']}

  3. {cars: ['], houses: ['ben'], ships: ['ben']}

The sort should be: 1, 3, 2

I achieved this by using function_score and filters:

for each filed I made a filter:

                "filter": {
                  "match": {
                    "cars.value": "ben"
                "weight": 1

This works, however not perfectly because elasticsearch decreases the score if my property is inside a deep object, the deeper it is the less score I will get.

Hope this can be changed.

However, the biggest issue is that I also want to count the matched elements in my property, let's say in cars I have ['ben', 'ben'] or wildcarded: ['ben', 'ben253'] I want to add additional point of 0.5 for each matched value in the array, and after a lot of research I figured out that you can't really count matched elements, you can count elements with a script but not the matched ones.

Is there a way to do this with elasticsearch query?

If not, how can I create such plugin? are there similar examples, any documentation on where to start?

Thanks a lot!

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.