Calculations using ruby filter in logstash is giving ruby exception error

I want to store multiplication of two fields in another field but when i run it gives ruby exception error. I am new to logstash and any help is appreciated. Thanks in advance for help.

mutate
{
add_field =>
{
"total_price" => "%{product_price}"
}
convert =>
{
"product_quantity" => "integer"
"product_price" => "integer"
"total_price" => "integer"
}
}
ruby
{
code => "event['total_price'] = event['product_price'].to_i * event['product_quantity'].to_i"
}

Error:
[2019-07-02T06:26:18,169][ERROR][logstash.filters.ruby ] Ruby exception occurred: undefined method []' for #<LogStash::Event:0x34990684> [2019-07-02T06:26:18,199][ERROR][logstash.filters.ruby ] Ruby exception occurred: undefined method' for #LogStash::Event:0xcbc1b3b
[2019-07-02T06:26:18,220][ERROR][logstash.filters.ruby ] Ruby exception occurred: undefined method []' for #<LogStash::Event:0x60d2e656> [2019-07-02T06:26:18,242][ERROR][logstash.filters.ruby ] Ruby exception occurred: undefined method' for #LogStash::Event:0x63762b11

In any version of logstash from the last couple of years you have to use the event API to reference or modify fields on the event. I have not tested it, but I think that would be

code => 'event.set("total_price", event.get("product_price").to_i * event.get("product_quantity").to_i)'

I always use ' to surround the code option so that I can use " around fields within the option, which means I can invoke string magic like interpolation.

I tried this method before but it did'nt work due to some error but now it did. Thanks a lot for your help!

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