RUBY Filter to event.set each entity in an Array

I am stuck on how to use a Ruby script to manipulate a field with in an array. If anyone can help with this I need to take the Field "[body][entities][sentiment][confidence]" and * 100 and add that as another Field "[body][entities][sentiment][probability]" for each entity
Example

if [body][entities][sentiment][label] == "pos"
  {
ruby { code => 'event.set("[body][entities][sentiment][probability]" , (event.get("[body][entities][sentiment][confidence]").to_f * 100)).to_f' }
  }

Here is the Single JSON Document.

{
  "_index": "logstash-2021.02",
  "_type": "_doc",
  "_id": "1111",
  "_score": 1,
  "_source": {
    "body": {
      "entities": [
        {
          "normalized": "NAME1",
          "sentiment": {
            "label": "pos",
            "confidence": 0.5776256
          }
        },
        {
          "normalized": "NAME2",
          "sentiment": {
            "label": "pos",
            "confidence": 0.47355394
          }
        },
        {
          "normalized": "NAME3",
          "sentiment": {
            "label": "pos",
            "confidence": 0.57258118
          }
        },
        {
          "normalized": "NAME4",
          "sentiment": {
            "label": "pos",
            "confidence": 0.61671584
          }
        }
      ]
    },
    "reference": "TEST",
    "@timestamp": "2021-02-05T09:00:11.000Z",
    "tags": [
      "TEST"
    ],
    "@version": "1",
    "type": "document"
  },
  "fields": {
    "@timestamp": [
      "2021-02-05T09:00:11.000Z"
    ]
  }
}

I have not tested it but you would have to do something like

ruby {
    code => '
        entities = event.get("[body][entities]")
        if entities.is_a? Array
            entities.each_index { |x|
                entities[x]["sentiment"]["probability"] = entities[x]["sentiment"][confidence] * 100
            }
            event.set("[body][entities]", entities)
        end
    '
}

It worked just missed some quotes around [confidence] * 100 should be ["confidence"] * 100
Was also able to add some if's in there for different formulas.
Thanks again for the help.

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