Getting sum of a field in xml

hi, i am new to elk. with a lot of googling and checking responses of @Badger i was able to come up with a working config to load data as i wanted.

sample loaded data

{
"@timestamp" => xxx,
"host" => "xxx",
"data" => {
"pmAverageSirError" => "3354,860,908,1053,1414,1868,1263,1603,1607,2122,1538,2226,1701,1911,1735,2866,2196,2572,3087,4539,8700,40007,9578,1393,708,382,304,217,172,119,90,79,65,57,62,42,38,35,25,22,22,171",
"measObjLdn" => "ManagedElement=xxx,NodeBFunction=1,NodeBLocalCellGroup=1,NodeBLocalCell=xxx,RadioLinks=1"
},
"tags" => [
[0] "multiline",
[1] "_rubyexception"
],
"@version" => "1",
"path" => "xxx"
}

now i want to sum a field so i tried

ruby {
code => '
a = event.get("[data][pmAverageSirError]")
if a
sum = 0
a.each_index { |x|
sum += a.to_i

		        }
		        event.set("sum_pmAverageSirError", sum)
				event.set("test", a)
		    end
		'
	}

please support.

Ruby arrays are Enumerable, and the Enumerable module has a sum function.

    ruby {
        code => '
            a = event.get("[data][pmAverageSirError]")
            if a
                a = a.split(",")
                a.each_index { |x| a[x] = a[x].to_i }
                event.set("sum_pmAverageSirError", a.sum)
            end
        '
    }
1 Like

thanks for the reply. it works. is it possible from my previous config that i can move everything our of data array and have only the actual fields and values?

i am using a code provided by you in some thread.

        xml { source => "message" target => "[@metadata][theXML]" force_array => true }
    ruby {
        code => '
            xml = event.get("[@metadata][theXML]")
            types = xml["measType"]
            values = xml["measValue"]
            a = []
            values.each { |x|
                h = {}
                h["measObjLdn"] = x["measObjLdn"]
                x["r"].each_index { |i|
                    h[types[i]["content"]] = x["r"][i]["content"]
                }
                a << h
            }
            event.set("data", a)
        '
    }
	
			if ([data]) {
				split { field => "[data]" }
				}

To move sub-fields to the top level you can use code like this.

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