Overview

array_slice

Usage#

Syntax#

array_slice(array, start, end)

Parameters#

Parameter Description
array The input array to slice.
start The starting index of the slice (inclusive). If negative, it’s counted from the end of the array.
end The ending index of the slice (exclusive). If negative, it’s counted from the end of the array.

Returns#

An array containing the elements from the specified slice. If the indices are out of bounds, it adjusts to return valid elements without error.

Use case example#

Filter spans from trace data to analyze a specific range of events.

Query

['otel-demo-traces']
| where array_length(events) > 4
| extend sliced_events = array_slice(events, -3, -1)

Run in Playground

Output

events

[
  {
    "timestamp": 1734001336443987200,
    "attributes": null,
    "name": "prepared"
  },
  {
    "attributes": {
      "feature_flag.provider_name": "flagd",
      "feature_flag.variant": "off",
      "feature_flag.key": "paymentServiceUnreachable"
    },
    "name": "feature_flag",
    "timestamp": 1734001336444001800
  },
  {
    "name": "charged",
    "timestamp": 1734001336445970200,
    "attributes": {
      "custom": {
        "app.payment.transaction.id": "49567406-21f4-41aa-bab2-69911c055753"
      }
    }
  },
  {
    "name": "shipped",
    "timestamp": 1734001336446488600,
    "attributes": {
      "custom": {
        "app.shipping.tracking.id": "9a3b7a5c-aa41-4033-917f-50cb7360a2a4"
      }
    }
  },
  {
    "attributes": {
      "feature_flag.variant": "off",
      "feature_flag.key": "kafkaQueueProblems",
      "feature_flag.provider_name": "flagd"
    },
    "name": "feature_flag",
    "timestamp": 1734001336461096700
  }
]

sliced_events

[
  {
    "name": "charged",
    "timestamp": 1734001336445970200,
    "attributes": {
      "custom": {
        "app.payment.transaction.id": "49567406-21f4-41aa-bab2-69911c055753"
      }
    }
  },
  {
    "name": "shipped",
    "timestamp": 1734001336446488600,
    "attributes": {
      "custom": {
        "app.shipping.tracking.id": "9a3b7a5c-aa41-4033-917f-50cb7360a2a4"
      }
    }
  }
]

Slices the last three events from the events array, excluding the final one.

Other query languages#

Splunk SPL users

In Splunk SPL, you can use mvindex to extract elements from an array. APL's array_slice is similar but more expressive, allowing you to specify slices with optional bounds.

Splunk example

| eval sliced_array=mvindex(my_array, 1, 3)

APL equivalent

T | extend sliced_array = array_slice(my_array, 1, 3)
ANSI SQL users

In ANSI SQL, arrays are often handled using JSON functions or window functions, requiring workarounds to slice arrays. In APL, array_slice directly handles arrays, making operations more concise.

SQL example

SELECT JSON_EXTRACT(my_array, '$[1:3]') AS sliced_array FROM my_table

APL equivalent

T | extend sliced_array = array_slice(my_array, 1, 3)

Updated

Was this page helpful?