Sort

Learn about the Sort OTTL converter function.

The Sort converter sorts a slice in ascending or descending order.

Syntax: Sort(target, Optional[order])

  • target: a slice containing elements to be sorted
  • order: an optional string specifying sort order: "asc" (default) or "desc"

The Sort converter preserves the data type of the original elements while sorting. The behavior varies based on the types of elements:

Element TypesSorting BehaviorReturn Value
IntegersSorts as integersSorted array of integers
DoublesSorts as doublesSorted array of doubles
Integers and doublesConverts all to doubles, then sortsSorted array of integers and doubles
StringsSorts as stringsSorted array of strings
BooleansConverts all to strings, then sortsSorted array of booleans
Mix of integers, doubles, booleans, and stringsConverts all to strings, then sortsSorted array of mixed types
Any other typesN/AReturns an error

Example 1: Sorting integers in ascending order (default)

Input

{
	"_type": "log",
	"body": {
		"unsorted": [5, 2, 8, 1],
		"run": 23
	},
	"resource": {...},
	"timestamp": 1727750400000
}

Statement

set(body["sorted"], Sort(body["unsorted"]))

Output

{
	"_type": "log",
	"body": {
		"unsorted": [5, 2, 8, 1],
		"sorted": [1, 2, 5, 8],
		"run": 23
	},
	"resource": {...},
	"timestamp": 1727750400000
}

The array [5, 2, 8, 1] was sorted in ascending order to produce [1, 2, 5, 8].

Example 2: Sorting in descending order

Input

{
	"_type": "log",
	"body": {
		"tags": ["warning", "error", "debug", "info"],
		"run": 24
	},
	"resource": {...},
	"timestamp": 1727750400000
}

Statement

set(body["sorted_tags"], Sort(body["tags"], "desc"))

Output

{
	"_type": "log",
	"body": {
		"tags": ["warning", "error", "debug", "info"],
		"sorted_tags": ["warning", "info", "error", "debug"],
		"run": 24
	},
	"resource": {...},
	"timestamp": 1727750400000
}

The string array was sorted in descending (reverse alphabetical) order.