23

I have no Java experience and I have an issue with elasticsearch painless script language. (the name painless it's not well chosen).

For the following code I get the error:

{"lang": "painless",
"inline": "float price = doc['newPrice'] > 0.0 ? doc['price'] / doc['newPrice'] : 0; _score * params.constant * price",
"params": {"constant": 1.2}}}}

Cannot apply [>] operation to types [org.elasticsearch.index.fielddata.ScriptDocValues.Doubles] and [java.lang.Double].

I tied to cast it as float with (float) doc['newPrice'] > 0 with the same error.

Then I changed to "Double price = ((Double)doc['discountPrice'] > 0.0) ? doc['price'] / doc['discountPrice'] : 0; _score * params.constant * price",

And received:

'Cannot cast from [Double] to [double].'

Can somebody help me, tried lots of variations with similar kind of errors. Damn painless language...

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Alexandru R
  • 8,560
  • 16
  • 64
  • 98

2 Answers2

47

You're simply missing the .value to access the field value.

Your script needs to be like this instead:

double price = doc['newPrice'].value > 0.0 ? doc['price'].value / doc['newPrice'].value : 0; _score * params.constant * price
Val
  • 207,596
  • 13
  • 358
  • 360
  • 1
    Val, do you also know how can I check if a field exists, so I can reference it's value? – Alexandru R Dec 27 '16 at 16:36
  • 1
    You can check for `doc['newPrice'].size()`. If you get 0, then there's no value, otherwise, there's a value you can use. – Val Dec 27 '16 at 16:39
  • @Val This is a very interesting question on painless script. https://stackoverflow.com/questions/53476036/check-value-exists-in-params-array-using-elasticsearch-painless-script – Anam Nov 26 '18 at 23:22
6
doc['newPrice']

is different from

doc['newPrice'].value

You should use the later

Sunil Purushothaman
  • 8,435
  • 1
  • 22
  • 20