I want to sort items by the array of numbers

Hello! I am using elasticsearch version 7.11 and I want to sort items by the array of numbers: lucky_numbers.number_list

A have a lot of elements like below and arrays have a dynamic length, example:

_source {
     "game.name": "Twisted Game",
     "lucky_numbers": [
     {
      "number_list": "9"
     },
     {
      "number_list": "11"
     },
     {
      "number_list": "102"
     }
     ]
 },
 ....
  _source {
     "game.name": "Number Roulette",
     "lucky_numbers": [
     {
      "number_list": "10"
     },
     {
      "number_list": "11"
     },
     {
      "number_list": "99"
     },
     {
      "number_list": "102"
     }
     ]
 },
 ....
  _source {
     "game.name": "Numeric Odyssey",
     "lucky_numbers": [
     {
      "number_list": "9"
     },
     {
      "number_list": "12"
     },
     {
      "number_list": "100"
     }
     ]
 }

If I use a sorting script and concatenate these sorted numbers into a string, I get the order:

"10,11,99,102"
"9,11,102",
"9,12,100"

But I want the correct numerical order:
"9,11,102",
"9,12,100"
"10,11,99,102"

How can I do this? I know that sort have e.g. option mode:min for arrays, but I want to consider all numbers in array, not just the lowest value. Can I write my own comparator?

Hi @CookiesPrompt

I noticed that there are some answers here to your question. However, I believe that when working with arrays and scripts it would be good to be careful with the performance of the search query.
As you said, this array does not have a fixed size and depending on that, your search queries may not have the expected performance.

If that's not a concern, it's fine to use scripts. I usually always try to index the data in a way that it is not necessary to do this type of manipulation, for example: you need to sort the array but wouldn't it be better to index the document with the sorted array? Your application can do this or if you want to leave this responsibility to elasticsearch, you can create a pipeline that will sort this array and index it in the sorting you want. This avoids the use of scripts in the search query.

Of course, once you remove the search script and start using it at indexing time, the index time may increase but if this is not a strong requirement for you, then it may be acceptable.

Anyway, you already have the answers in another forum but I believe it is worth paying attention to the other points.

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