简体   繁体   English

每次出现该事件时,在 logstash 中使用 Ruby 过滤器对字段的值求和

[英]Using Ruby filter in logstash to sum values of a field everytime that event appears

I'm trying to sum the value of a specific field every time it shows, the field is in this format: [cdr][Service-Information][PS-Information][Service-Data-Container][Accounting-Output-Octets] and its value is a numeric field (it shows the number of bits consumed).我试图在每次显示时对特定字段的值求和,该字段采用以下格式: [cdr][Service-Information][PS-Information][Service-Data-Container][Accounting-Output-Octets]并且它的值是一个数字字段(它显示消耗的位数)。

What I'm trying to do is the following:我正在尝试做的是以下内容:

a = event.get("[cdr][Service-Information][PS-Information][Service-Data-Container][Accounting-Output-Octets]")
if a
    sum = 0
    a.each_index { |x|
        sum += a["amount"]
    }
    event.set("amount-sum", sum)
end

I'm getting the following error:我收到以下错误:

Ruby exception occurred: undefined method `each_index' for Integer发生 Ruby 异常:整数的未定义方法“each_index”

I am a newbie in Ruby, so I've got no idea if this code serves for this type of field too.我是 Ruby 的新手,所以我不知道这段代码是否也适用于这种类型的领域。

If a is integer You can use something like this:如果 a 是整数你可以使用这样的东西:

a = 123456789
a = a.to_s.split("").map(&:to_i)
sum = 0
a.each do |x|
  sum += x
end
p sum #=> 45

And please DO NOT USE brace if block is not in one line.如果块不在一行中,请不要使用大括号。 Here I did it with do end just to show how it must be.在这里,我用 do end 完成它只是为了展示它必须是怎样的。 If You want to use one line block - You must write like that:如果你想使用一行代码块 - 你必须这样写:

a.each {|x| sum += x} 

if block > 1 lines than use do/end |如果块 > 1 行比使用 do/end | else { }别的 { }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM