Using boolean fields in a groovy script in elasticsearch is doc ['field_name']. Value does not work

Problem

I am trying to use boolean fields in a script for evaluation. It looks like doc ['boolean_field']. The value cannot be manipulated as a boolean, but _source.boolean_field.value can (although the scripting documentation says: Native field value. For example, if its type is short, it will be short. ").

What i tried

I have a field 'is_new'. This mapping is:

PUT /test_index/test/_mapping { "test": { "properties": { "is_new": { "type": "boolean" } } } } 

I have several documents:

 PUT test_index/test/1 { "is_new": true } PUT test_index/test/2 { "is_new": false } 

I want to make a function_score request that will have a score of 1 if new, and 0 if not:

 GET test_index/test/_search { "query": { "function_score": { "query": { "match_all": {} }, "functions": [ { "script_score": { "script": "<<my script>>", "lang": "groovy" } } ], "boost_mode": "replace" } } } 

The scripts work when I use the _source.is_new.value field but don’t use the doc ['is_new'] value.

It works:

 "if ( _source.is_new) {1} else {0}" 

They do not work:

 "if ( doc['is_new'].value) {1} else {0}" (always true) "if ( doc['is_new'].value instanceof Boolean) {1} else {0}" (value isn't a Boolean) "if ( doc['is_new'].value.toBoolean()) {1} else {0}" (always false) "if ( doc['is_new']) {1} else {0}" (always true) 

I checked the value and it considers it to be a string, but I cannot perform string comparison:

 "if ( doc['is_new'].value instanceof String) {1} else {0}" (always true) "if ( doc['is_new'].value == 'true') {1} else {0}" (always false) "if ( doc['is_new'].value.equals('true')) {1} else {0}" (always false) 

Is it broken or am I doing it wrong? It seems to be faster to use the doc ['field_name'] value. Therefore, if possible, it would be nice if that worked.

I am using Elasticsearch v1.4.4.

Thanks! Isabel

+6
source share
2 answers

I have the same problem on ElasticSearch v1.5.1: Boolean values ​​in the document are displayed as characters in my script, T 'for true and' F 'for false:

if ( doc['is_new'].value == 'T') {1} else {0}

+5
source

I just got it!

First, it only works with _source.myField, not with doc ['myField']. I think there is an error there, because the toBoolean () method should return a boolean value depending on the actual value, but that is not the case.

But I also needed to declare the display of the field explicitly as boolean and not_analyzed.

Hope this helps!

+2
source

Source: https://habr.com/ru/post/985723/


All Articles