Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elasticsearch painless script error

Tags:

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...

like image 793
Alexandru R Avatar asked Dec 27 '16 15:12

Alexandru R


People also ask

What is painless script in Elasticsearch?

Painless is a performant, secure scripting language designed specifically for Elasticsearch. You can use Painless to safely write inline and stored scripts anywhere scripts are supported in Elasticsearch.

How do you debug a painless script?

Debug. For now the best way to debug embedded scripts is by throwing exceptions at choice places. While you can throw your own exceptions ( throw new Exception('whatever') ), Painless's sandbox prevents you from accessing useful information like the type of an object.

What is CTX in Elasticsearch?

ctx is a special variable that allows you to access the source of the object that you want to update. The ctx. _source is a writable version of the source . NOTE: You can modify this document in the script and the modified source will be persisted as the new version of the document.

How do I write a script in Elasticsearch?

Wherever scripting is supported in the Elasticsearch APIs, the syntax follows the same pattern; you specify the language of your script, provide the script logic (or source), and add parameters that are passed into the script: "script": { "lang": "...", "source" | "id": "...", "params": { ... } }


2 Answers

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 
like image 181
Val Avatar answered Sep 30 '22 21:09

Val


doc['newPrice'] 

is different from

doc['newPrice'].value 

You should use the later

like image 30
Sunil Purushothaman Avatar answered Sep 30 '22 21:09

Sunil Purushothaman