Skip to content

min_by - Calculate the max value of expression for each sort key

The min_by function will calculate the minimum value of an expression for each sort key

Syntax

min_by(sortKey: T, expression: U): U

Arguments

NameTypeRequiredDescription
sortKeyTtrueT must be either string, bool, number, interval, timestamp, regexp or enum
expressionUtrueU must be either string, bool, number, interval, timestamp, regexp or enum

Example - Computing details of earliest event

Consider the following documents:

{
    "username": "chris",
    "path": "/home",
    "latency": 320,
    "ts": 1728919749261000000
},
{
    "username": "chris"
    "path": "/checkout",
    "latency": 5000,
    "ts": 1728919759261000000
}

I want to know what was the first activity that chris did. To do this, I can use min on the ts field to work out the latest timestamp, and I can use min_by to extract the values I need:

source logs | groupby username agg
  min(ts) as ts,
  min_by(ts, path) as path

This results in the following document:

{
    "username": "chris"
    "path": "/checkout",
    "ts": 1728919759261000000
}

Note that the path corresponds to the path value for the original event that had the earliest ts value. This is the power of min_by.