Can I add leading zeros to a field?


(David Reynolds) #1

Question about Logstash (Elastic Stack). Can someone give me a pointer on how to add a new field (add_field) that will format a number with leading zeroes?
e.g. given somefield == 123 then someotherfield == "00123".


(Magnus Bäck) #2

Do you always want to leading zeroes or do you always want the string to be five characters long? (Either way the answer would be to use a mutate filter's gsub option, but an exact answer depends on the details.)


(David Reynolds) #3

Yes.and yes. Always leading zeroes always five chars long.


(Magnus Bäck) #4

Unless the field already is a string use a mutate filter's convert option to coerce it into a string. Then do this:

if [somefield] =~ /^\d{3}$/ {
  mutate {
    replace => {
      "somefield" => "00%{somefield}"
    }
  }
}

This one takes care of strings of length three that need to zeroes prepended. Repeat to support strings of different lengths.

You could also use a ruby filter. Such a configuration would be more compact and possibly faster.


(David Reynolds) #5

Thank you Magnus


(system) #6

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