# Logstash - ruby script to create array of nested fields

**URL:** <https://discuss.elastic.co/t/logstash-ruby-script-to-create-array-of-nested-fields/200312>\
**Category:** Logstash\
**Created:** [September 19, 2019, 9:01pm UTC](https://discuss.elastic.co/t/logstash-ruby-script-to-create-array-of-nested-fields/200312 "2019-09-19T21:01:44Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![Badger](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/badger/32/25190_2.png) [@Badger](https://discuss.elastic.co/u/Badger)\
**Post date:** [September 19, 2019, 10:50pm UTC](https://discuss.elastic.co/t/logstash-ruby-script-to-create-array-of-nested-fields/200312/2 "2019-09-19T22:50:08Z")

</div>

I was really surprised at how ugly the code I wrote to do this is. I feel there should be a much easier way.

```
    ruby {
        code => '
            a = []
            u = event.get("Unit")
            h1 = {}
            h2 = {}

            u.each { |k,v|
                h1[k] = v[0]
                h2[k] = v[1]
            }
            a << h1
            a << h2
            event.set("MonsiuerSpalanzani", a)
        '
        remove_field => ["Unit"]
    }
    split { field => "MonsiuerSpalanzani" }
    ruby {
        code => '
            event.get("MonsiuerSpalanzani").each { |k,v|
                event.set(k, v)
            }
        '
        remove_field => ["MonsiuerSpalanzani"]
    }

```

Hmm. Thinking about it, this would be much cleaner if done as a ruby script file, since that can return an array of events, so the split would not be needed. If you create a file called invertUnits.rb containing

```
def register(params)
    @field = params['field']
end

def filter(event)
    newEvents = []

    o = event.get(@field)
    if !o
      newEvents << event
    else
      (0..1).each { |n|
        e = LogStash::Event.new
        o.each { |k, v|
          e.set(k, v[n])
        }

        ["@timestamp", "@version", "host", "sequence"].each { |k|
          v = event.get(k)
          if v
            e.set(k, v)
          end
        }

        newEvents << e
      }
    end

    newEvents
end

```

then call it using

```
    ruby {
        path => "/home/user/invertUnits.rb"
        script_params => { "field" => "Unit" }
    }
```

---

_[View the full topic](https://discuss.elastic.co/t/logstash-ruby-script-to-create-array-of-nested-fields/200312)._
