Convert values in kv-pairs (using ruby filter)


(Oleg Aroslanov) #1

Hi there!
There was a topic already for that: https://discuss.elastic.co/t/convert-values-in-kv-pairs/39904
but the solution no longer works due to syntax changes in new version.
Could anyone please advise what it should look like now?
old syntax looks like this:

ruby{ code => " kv = event['kvpairs'] kv.to_hash.keys.each { |k| if kv[k].include? '.' kv[k] = kv[k].to_f else kv[k] = kv[k].to_i end } " }


#2

You have to use event.get/set now. And in case you ever have non-numerics in the set...

            kv = event.get('kvpairs')
            kv.to_hash.keys.each { |k|
                if kv[k].to_i.to_s == kv[k]
                    kv[k] = kv[k].to_i
                end
                if kv[k].to_f.to_s == kv[k]
                    kv[k] = kv[k].to_f
                end
            }
            event.set('kvpairs', kv)
        "


(Oleg Aroslanov) #3

Thanks @Badger !
But now there is another error:

Ruby exception occurred: undefined method `to_hash' for nil:NilClass


#4

Is the field actually called kvpairs? Doing a event.get on that returned nil.


(Oleg Aroslanov) #5

Yes it was. I have found what was wrong, instead of to_hash now it should be to_h


(system) #6

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