- 2 minutes to read

Formula - Average (avg)

The avg function, one of the Math functions in the Formula plugin for Search Field Expressions, returns the average of the numeric values in the content.

Syntax

avg(content [, unique])

Parameters

Parameter Required Description
content ✅ Yes The numeric values to average: body, context, or another Formula function such as xPath or jsonPath.
unique ❌ No Unquoted true or false; default false for this function. false: a value that appears several times counts every time. true: identical values count once. Values are compared as text, so 100 and 100.00 are different values. A quoted 'true' is an error.

Returns

  • One number: the average (mean) of the numeric values in content.
  • When content holds no numeric value, avg returns nothing.

Quoting, nesting, and how content is resolved are described in the Formula language rules.

Examples

Example 1: Average the order amounts in an XML message

Input

Message Body:

<ns0:Orders xmlns:ns0="SupplyChain.Schemas/1.0">
  <Order>
    <Id>1337</Id>
    <Amount>4</Amount>
    <City>New York</City>
    <Partner>QWNtZQ==</Partner>
  </Order>
  <Order>
    <Id>1338</Id>
    <Amount>2</Amount>
    <City>Paris</City>
    <Partner>QWNtZQ==</Partner>
  </Order>
</ns0:Orders>

Formula

avg(xPath('Orders/Order/Amount', body))

Result

3

xPath extracts the amounts 4 and 2; their average is 3.

Test Expression tab: avg(xPath('Orders/Order/Amount', body)) on two orders with amounts 4 and 2 returns 3
The namespace prefix ns0: doesn't need to be part of the XPath; Orders/Order/Amount matches it.

Example 2: Average numeric values extracted from JSON

Input

Message Body:

{"a":[{"b":1},{"b":2},{"b":6}]}

Formula

avg(jsonPath('a[*].b', body))

Result

3

jsonPath extracts 1, 2, and 6; their average is 3.

Test Expression tab: avg of jsonPath over every b in the array a, on the JSON values 1, 2, and 6, returns 3
a[*].b selects b in every element of the array a; the result is one number, not three.

Notes

  • By default every occurrence counts: lines of 100, 100, and 400 average 200. With avg(..., true) identical values count once, so the average is (100 + 400) / 2 = 250.

Next Steps