Script sorting retun type exception

I'm trying to sort query results based on script. As nested _script has type number, for missing value return null throwing exception and return 0 or -1 are useless. Here is error message "Cannot cast null to a primitive type [double]"

sorting as

"sort": [{
"_script": {
"nested": {
"path": "currency_prices"
},
"type": "number",
"order": "asc",

        "script": {
          "lang": "painless",
          "inline": "if(doc['currency_prices.currency'].value != params.currency){ return null; }else{ return doc['currency_prices.price'].value }",
          "params": {
            "currency": "USD"
          }
      }
    }
			}]

any help please?

Your script should return some proper numeric values, not null. You should redesign your script to return some proper numeric value, e.g 0.

If you need to filter some nested documents and exclude them from sorting you can use a filter:

"nested" : {
        "path" : "my_nested",
        "filter": {
          "match": {"currency_prices.currency": "USD"}
        }
}

I would redesign a sort part of your request into something like this:

"sort": {
    "_script": {
      "order": "asc",
      "nested": {
        "path": "currency_prices",
        "filter": {
          "match": {
            "currency_prices.currency": "USD"
          }
        }
      },
      "type": "number",
      "script": {
        "source": "doc['currency_prices.price'].value"
      }
    }
  }
1 Like

thanks @mayya i used mode: max for sorting which worked exactly as expected. But, i guess my approach is a bit expensive in terms of response time. Will try your script for sure. Also i will be very thankful if you can tell me the better one. thanks again

here is my script version

"sort": {
"_script": {
"nested": {
"path": "currency_prices"
},
"type": "number",
"order": "asc",
"mode" : "max",
"script": {
"lang": "painless",
"inline": "def price = -1; if (doc['currency_prices.currency'].value == params.currency) { price = doc['currency_prices.price'].value;} price;",
"params": {
"currency": "CAD"
}
}
}
}

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