topk

This page explains how to use the topk aggregation function in APL.

The topk aggregation in Axiom Processing Language (APL) allows you to identify the top k results based on a specified field. This is especially useful when you want to quickly analyze large datasets and extract the most significant values, such as the top-performing queries, most frequent errors, or highest latency requests.

Use topk to find the most common or relevant entries in datasets, especially in log analysis, telemetry data, and monitoring systems. This aggregation helps you focus on the most important data points, filtering out the noise.

Usage

Syntax

topk(Field, k)

Parameters

  • Field: The field or expression to rank the results by.
  • k: The number of top results to return.

Returns

A subset of the original dataset with the top k values based on the specified field.

Use case examples

When analyzing HTTP logs, you can use the topk function to find the top 5 most frequent HTTP status codes.

Query

['sample-http-logs']
| summarize topk(status, 5)

Run in Playground

Output

statuscount_
2001500
404400
500200
301150
302100

This query groups the logs by HTTP status and returns the 5 most frequent statuses.

In OpenTelemetry traces, you can use topk to find the top five status codes by service.

Query

['otel-demo-traces']
| summarize topk(['attributes.http.status_code'], 5) by ['service.name']

Run in Playground

Output

service.nameattributes.http.status_code_count
frontendproxy20034,862,088
2033,095,223
404154,417
500153,823
5043,497

This query shows the top five status codes by service.

You can use topk in security log analysis to find the top 5 cities generating the most HTTP requests.

Query

['sample-http-logs']
| summarize topk(['geo.city'], 5)

Run in Playground

Output

geo.citycount_
New York500
London400
Paris350
Tokyo300
Berlin250

This query returns the top 5 cities based on the number of HTTP requests.

  • top: Returns the top values based on a field without requiring a specific number of results (k), making it useful when you’re unsure how many top values to retrieve.
  • topkif: Returns the top k results without filtering. Use topk when you don’t need to restrict your analysis to a subset.
  • sort: Orders the dataset based on one or more fields, which is useful if you need a complete ordered list rather than the top k values.
  • extend: Adds calculated fields to your dataset, which can be useful in combination with topk to create custom rankings.
  • count: Aggregates the dataset by counting occurrences, often used in conjunction with topk to find the most common values.

Other query languages