Subtraction between 2 different fields(with scripted fields)

Hello!

I converted a string into int using scripted fields. Now I am trying to subtract this field with another field inside the the index pattern. My document looks something like this:

{
  "_source": {
   "type": "example",
   "example": {
    "value1": 000,
    "value_to_subtract": 6
    },
  "fields": {
    "test1": [
      000
    ],
    "test2_int_to_subtract": [
      8
    ],
    "timestamp": [
      "0000-00-00T00:00:00.000Z"
    ]
  }
}

So I am creating a scripted field like that
doc['test2_int_to_subtract'].value - doc['example.value_to_subtract'].value,
however I have shard failure in discover.

org.elasticsearch.search.lookup.LeafDocLookup.get(LeafDocLookup.java:94)
org.elasticsearch.search.lookup.LeafDocLookup.get(LeafDocLookup.java:41)
doc['test2_int_to_subtract'].value - doc['example.value_to_subtract'].value
    ^---- HERE

What am I doing wrong?
Thank you very much in advance!

/Angelos

Hi & Welcome back!
Could you try

doc['fields.test2_int_to_subtract'].value - doc['example.value_to_subtract'].value

Thanks!
Matthias

Hi,
Thank you!

I tried that but still have the same error with this caused reason:

No field found for [fields.test2_int_to_subtract] in mapping with types []

Is it because the fields are not under the _source? Another thing that I am seeing is that under _source the fields are inside {} but under fields the scripted field is inside [].

Thank you in advance!

/Angelos

So it’s not part of the _source, how is ist set, could you share your indexpattern? Many thx!

When I create a scripted field and then see the document in Discover it puts it to "fields": (see first message)

{
  "_index": "test",
  "_type": "test",
  "_id": "test",
  "_version": 1,
  "_score": null,
  "_source": {
   "type": "example",
   "example": {
    "value1": 000,
    "value_to_subtract": 6
    },
  "fields": {
    "test1": [
      000
    ],
    "test2_int_to_subtract": [
      8
    ],
    "timestamp": [
      "0000-00-00T00:00:00.000Z"
    ]
  }
}

Basically I am trying to use(recalculate) an already existing scripted field.

Hi

You can't use the result of a scripted field in another scripted field. So you'd need to used to code of scripted field 1 in scripted field 2

(code of test2_int_to_subtract) - doc['example.value_to_subtract'].value

Best,
Matthias

1 Like

Hi,

Ok, thank you!

/Angelos

1 Like

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