Get the Last Element of an Array

Retrieve array element values using the getField() function

Query

logscale
index := array:length("foo[]")-1
| fieldName := format("foo[%s]", field=[index])
| result := getField(fieldName)

Introduction

Given an event with an array for field foo[x]:

foo['a','b','c','d']

Looks up the value of the field which is part of an array of elements, using getField() in combination with expressions: first build the string with the field, then perform getField() in that string to get the result.

Step-by-Step

  1. Starting with the source repository events.

  2. logscale
    index := array:length("foo[]")-1

    Sets the index as the last element of the array (in this case, [6])

  3. logscale
    | fieldName := format("foo[%s]", field=[index])

    Takes the field index and builds the string foo[6] using format()

  4. logscale
    | result := getField(fieldName)

    Provides the value of the field whose name is foo[6]

  5. Event Result set.

Summary and Results

The output is displayed as follows, where the last column shows the value of fieldName column (which is foo[3]) as the result:

@timestamp@rawstring@timestamp.nanosfieldNamefoo[0]foo[1]foo[2]foo[3]indexresult
2024-03-01T08:43:12{"foo": ["a","b","c","d"]}0foo[3]abcd3d