Getting length of array in Logstash using ruby filter


#1

I have a field, Ports, that is in arrays and is nested.

Examples of my data
"ports": ["TCP1", "TCP2", 'TCP3"]
"ports": ["UDP1", "UDP2"]

However each of these feeds have different number of elements in them. I have to strip the array brackets through the mutate replace filter but before that I need a ruby filter to retrieve the number of elements for each feed for a if-else check.

Desired Output:

filter {
     ruby {
         code => ??? Need help here with the code
     }
 
      mutate {
          if [number of elements] == 3 {
              replace => ["ports", "%{[port][0]} %{[port][1]} %{[port][2]}"]
          }
          else if [number of elements] == 2 {
              replace => ["ports", "%{[port][0]} %{[port][1]}"]
          }
        }
      }

(Paris Mermigkas) #2

To get the length of an array you can use this

ruby {
  code => "
    event.set('number_of_elements', event.get('ports').length)
  "
}

That said, if you just need to flatten the array and keep the information inside as a string, you can do the following instead of the whole conditional of your post (which removes the need for counting array lengths and the mutate filter).

ruby {
  code => "
    event.set('ports', event.get('ports').join(' '))
  "
}

This would convert

"ports": ["TCP1", "TCP2", 'TCP3"]

to

"ports": "TCP1 TCP2 TCP3"


(system) #3

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