Skip to content

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

The max_by function will calculate the maximum value of expression for each sort key

Syntax

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

Arguments

Name Type Required Description
sortKey T true T must be either string, bool, number, interval, timestamp, regexp or enum
expression U true U must be either string, bool, number, interval, timestamp, regexp or enum

Example - Computing details of latest 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 last activity that chris did. To do this, I can use max on the ts field to work out the latest timestamp, and I can use max_by to extract the values I need:

source logs | groupby username agg
  max(ts) as ts,
  max_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 latest ts value. This is the power of max_by.