map() function

The map() function applies a function to each record in the input tables. The modified records are assigned to new tables based on the group key of the input table. The output tables are the result of applying the map function to each record of the input tables.

When the output record contains a different value for the group key, the record is regrouped into the appropriate table. When the output record drops a column that was part of the group key, that column is removed from the group key.

*Function type: Transformation*

  1. map(fn: (r) => ({ _value: r._value * r._value }))

Parameters

Make sure fn parameter names match each specified parameter. To learn why, see Match parameter names.

fn

A single argument function to apply to each record. The return value must be a record.

*Data type: Function*

Records evaluated in fn functions are represented by r, short for “record” or “row”.

Important notes

Preserve columns

By default, map() drops any columns that:

  1. Are not part of the input table’s group key.
  2. Are not explicitly mapped in the map() function.

This often results in the _time column being dropped. To preserve the _time column and other columns that do not meet the criteria above, use the with operator to map values in the r record. The with operator updates a column if it already exists, creates a new column if it doesn’t exist, and includes all existing columns in the output table.

  1. map(fn: (r) => ({ r with newColumn: r._value * 2 }))

Examples

Square the value of each record
  1. from(bucket:"example-bucket")
  2. |> filter(fn: (r) =>
  3. r._measurement == "cpu" and
  4. r._field == "usage_system" and
  5. r.cpu == "cpu-total"
  6. )
  7. |> range(start:-12h)
  8. |> map(fn: (r) => ({ r with _value: r._value * r._value}))
Create a new table with new format
  1. from(bucket:"example-bucket")
  2. |> filter(fn: (r) =>
  3. r._measurement == "cpu" and
  4. r._field == "usage_system"
  5. )
  6. |> range(start:-12h)
  7. // create a new table by copying each row into a new format
  8. |> map(fn: (r) => ({
  9. time: r._time,
  10. app_server: r.host
  11. }))
Add new columns and preserve existing columns
  1. from(bucket:"example-bucket")
  2. |> filter(fn: (r) =>
  3. r._measurement == "cpu" and
  4. r._field == "usage_system"
  5. )
  6. |> range(start:-12h)
  7. // create a new table by copying each row into a new format
  8. |> map(fn: (r) => ({
  9. r with
  10. app_server: r.host,
  11. valueInt: int(v: r._value)
  12. }))

Related articles

exists