Math operations with ruby

I want to multiply or divide two fields and create a new field based on that. I've got this ruby code:

    ruby {
        code => "event['hit_rate'] = event['MAIN_client_req'] * event['MAIN_cache_hit']"
    }

When I try to use it I'm getting:

Ruby exception occurred: undefined method `*' for nil:NilClass {:level=>:error}
Ruby exception occurred: NilClass can't be coerced into Fixnum {:level=>:error}

This is a part of my logstash config:

    grok {
        match => { "message" => "(?<parameter>([^\s]+))" }
        match => { "message" => "(?<value>\s([0-9]+))" }
        match => { "beat" => "(?<hostname>(\w+\-\w+))" }
        break_on_match => false
    }
    mutate {
        gsub => [ "value", "\s", "" ]
        gsub => [ "parameter", "\.+", "_" ]
        convert => { "value" => "integer" }
        lowercase => [ "hostname" ]
        add_field => { "%{parameter}" => "%{value}" }
    ruby {
        code => "event['hit_rate'] = event['MAIN_client_req'] * event['MAIN_cache_hit']"
    }
1 Like

If you have solved this, sharing the solution would be great. It might help someone in the future.

1 Like

The problem I was having is that I wasn't convert them into integers with ruby so all I did was modify and add this (to_i):

    ruby { 
        code => "event['cache_hit_rate'] = event['MAIN_client_req'].to_i / event['MAIN_cache_hit'].to_i"
    }
2 Likes