Ruby snippet to iterate through array results in error "Ruby exception occurred: undefined method `[]' for #<LogStash::Event:0x69068bc1>`"

I've got the following xpath:

   xpath => [
     "/record/parameters/parameter/text()", "parameter" ]

Parameter is a field that can have a variable number of values, from 0 to n. So it can not exist, or it can have n values. I have the following Ruby:

  ruby {
    code => '
    ids = event["parameter"].split(",")  
    ids.each_with_index do |value, index|           
      event["parameter_%{index}"] = "value"           
    end
    '
  }

The error I get in the logs is:

[2020-03-04T16:30:32,520][ERROR][logstash.filters.ruby ] Ruby exception occurred: undefined method ' for #LogStash::Event:0x69068bc1`

I'm very new to Ruby so I'm assuming that there are a couple things missing, but my immediate questions are:

  1. Do I need to have a check preceeding the rest of my Ruby making sure that the parameter field exists and has values?
  2. Am I using the event function incorrectly?
  1. Yes

  2. No. See here.

I have gotten through all the errors I was facing, but now seem to be mucking up the loop for iterating the array.

My Ruby is now:

ruby {
    code => '
    parametersExist = event.get("parameter")
    if parametersExist
      ids = event.get("parameter") 
      ids.each_with_index do |value, index|           
        event.set("parameter_%{index}", "value")          
      end
    end
    '
  }

But it just makes a literal value:

Greenshot 2020-03-04 19.24.40

I've confirmed that the array has values (unless this isn't even an array):

Greenshot 2020-03-04 19.25.16

That's not how you do string interpolation in ruby. sprintf references are a logstash thing, not a ruby thing. Try

event.set("parameter_#{index}", value)

As a point of style I think it would be more common to do

ids = event.get("parameter")
if ids
    ...

thus getting rid of the intermediate variable.

That works! Thank you so much for your prompt responses. Here is the working code for anybody checking this thread later.

  ruby {
    code => '
    ids = event.get("parameter")
    if ids  
      ids.each_with_index do |value, index|           
        event.set("parameter_#{index}", value)          
      end
    end
    '
  }

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