Sorting on value from script field

Hello everyone,

The result of my executed query should be a number of documents including script fields, and optionally some sorting. The script fields rely on real-time data I am passing in the params, so the script fields cannot be calculated in advance.

Sorting on the existing fields works as expected. The problem I'm having is that I also want to be able to sort on the script fields. Some of the script fields are a hash map.

Example:
POST /asdf/1
{
"n": 1,
"multiplier": 1
}

POST /asdf/1
{
  "n": 2,
  "multiplier": 1
}

POST /asdf/1
{
  "n": 2,
  "multiplier": -1
}

GET /asdf/_search
{
  "script_fields": {
    "myField": {
      "script": {
        "source": """
        HashMap res = new HashMap();
        res.put('a', doc['n'].value * params['realTimeData']);
        res.put('b', doc['n'].value * doc['multiplier'].value * params['realTimeData']);
        return res;
        """,
        "params": {
          "realTimeData": 1
        }
      }
    }
  },
  "sort": [
    {
      "myField['a']": {
        "order": "desc"
      }
    }
  ]
} 

Thank you in advance.

You can't sort on a script field, because script fields are only calculated for the hits that are being returned. In other words, your hits have already been sorted before the script fields are calculated.

What you may want to look at instead is script based sorting. The docs have an example of that. What's nice about script based sorting is that the scripted values that are used for sorting will be returned with the hits. So you may not need the script fields if you use script based sorting

Hi Abdon,

Thank you for your reply.

In my case I want to return a HashMap. As far as I understand, the sorting is on numbers. Is there a way for me to calculate and return the entire HashMap while sorting on one value in the HashMap?

Without knowing the details of what you're trying to do, there's nothing stopping you from using both script based sorting and script fields at the same time. You could then sort on one calculated value, and return additional information with the script field.

My goal is to calculate a set of values. The reason why I want to calculate them together in one script is because they are interdependent. The reason why I would prefer to calculate them only once is because the calculations take some time.

It seems there is no way to return the complete hash map from the sorting script (yet), and, as you said, there is no way to sort on the script field. In that case there is no way around it and I will just have to do the calculations twice.

Thank you for the quick replies.

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