Create custom Flux functions

The basic syntax for defining functions in Flux is as follows:

functionName

The name used to call the function in your Flux script.

functionParameters

A comma-separated list of parameters passed into the function and used in its operations. Parameter defaults can be defined for each.

functionOperations

Basic function examples

Example square function
  1. square = (n) => n * n
  2. // Function usage
  3. > square(n:3)
  4. 9
Example multiply function
  1. // Function definition
  2. multiply = (x, y) => x * y
  3. // Function usage
  4. > multiply(x: 2, y: 15)
  5. 30

Most Flux functions process piped-forward data. To process piped-forward data, one of the function parameters must capture the input tables using the <- pipe-receive expression.

In the example below, the tables parameter is assigned to the <- expression, which represents all data piped-forward into the function. tables is then piped-forward into other operations in the function definition.

Pipe-forwardable function example

Multiply row values by x

The example below defines a multByX function that multiplies the column of each row in the input table by the x parameter. It uses the to modify each _value.

  1. // Function definition
  2. multByX = (tables=<-, x) => tables
  3. |> map(fn: (r) => ({r with _value: r._value * x}))
  4. // Function usage
  5. from(bucket: "example-bucket")
  6. |> range(start: -1m)
  7. |> filter(fn: (r) => r._measurement == "mem" and r._field == "used_percent")
  8. |> multByX(x: 2.0)
  1. functionName = (param1=defaultValue1, param2=defaultValue2) => functionOperation

Defaults are overridden by explicitly defining the parameter in the function call.

Get a list of leaders

The example below defines a leaderBoard function that returns a limited number of records sorted by values in specified columns. It uses the to sort records in either descending or ascending order. It then uses the limit() function to return a specified number of records from the sorted table.

To create custom functions with variables scoped to the function, place your function operations and variables inside of a and use a return statement to return a specific variable.

  1. return exampleVar
  2. }

Example functions with scoped variables

Return an alert level based on a value

  1. alertLevel = (v) => {
  2. level = if float(v: v) >= 90.0 then
  3. "crit"
  4. else if float(v: v) >= 80.0 then
  5. "warn"
  6. else if float(v: v) >= 65.0 then
  7. "info"
  8. else
  9. "ok"
  10. return level
  11. }
  12. // Returns "warn"

Convert a HEX color code to a name

The following function converts a hexadecimal (HEX) color code to the equivalent HTML color name. The functions uses the to create a dictionary of HEX codes and their corresponding names.