Skip to content

DQL Function Reference


DQL provides a rich set of functions for data aggregation, transformation, and matching. This document describes the semantics, parameters, and usage of each function in detail.

Aggregation Functions

Aggregation functions aggregate multiple rows of data into a single value. They are usually used with a time window (time-expr) and grouping (BY clause).

Results from sum, average, extrema, range, standard deviation, and percentile retain the unit of the input field and are not automatically converted. Results such as counts, rates, and ratios must be interpreted according to the statistical definition of the corresponding function.

Basic Aggregations

sum

Calculates the sum of field values.

Syntax:

sum(field)

Parameters:

  • field: Numeric field

Examples:

# bytes indicates the number of bytes transferred by each log record
L::access_logs:(sum(bytes)) [1h]

# Calculate total bytes transferred by service
L::access_logs:(sum(bytes)) [1h] BY service

avg

Calculates the average value of a field.

Syntax:

avg(field)

Parameters:

  • field: Numeric field

avg calculates the arithmetic mean of samples and does not automatically weight by sampling duration.

Examples:

# Calculate average response time
M::response_time:(avg(duration)) [1h] BY endpoint

# Calculate average CPU usage
M::cpu:(avg(usage)) [1h] BY host

count

Calculates the number of data rows.

Syntax:

count(field)
count(*)

Parameters:

  • field: Any field; counts non-null values
  • *: Counts all rows

For example, if three records have field values 10, 0, and nil, count(*) is 3 and count(field) is 2. A field value of 0 does not mean the field is empty. To estimate the number of distinct values, use count_distinct; to count raw time series, use count_series.

Return value: Integer count.

Examples:

# Count log entries
L::nginx:(count(*)) [1h]

# Count requests that have a response time
M::response_time:(count(duration)) [1h] BY service

min / max

Calculates the minimum or maximum value of a field.

Syntax:

min(field)
max(field)

Parameters:

  • field: Numeric field

Examples:

# Find the maximum response time
M::response_time:(max(duration)) [1h] BY endpoint

# Find the range of CPU usage
M::cpu:(min(usage), max(usage)) [1h] BY host

first / last

Gets the first or last value (in chronological order).

Syntax:

first(field)
last(field)
last_row(field)

Parameters:

  • field: Any field

Description:

  • first: Returns the value with the earliest time
  • last: Returns the value with the latest time; if the field is an array type, it is expanded
  • last_row: Returns the value with the latest time; array types are not expanded

Examples:

# Get the latest status value
M::system:(last(status)) [1h] BY host

# Get the initial and final values
M::counter:(first(value), last(value)) [1h] BY metric

# Retain the entire tags array from the latest record
L::logs:(last_row(tags) AS latest_tags) [1h] BY service

first and last select values by chronological order, while min and max select values by numeric magnitude. The row in last_row does not mean that all fields of the last record are automatically returned.


any

Returns any non-null value. This is suitable for obtaining sample data or scenarios that do not require a specific aggregation order.

Syntax:

any(field)

Parameters:

  • field: Any field

To get the earliest or latest value by time, use first or last; any does not guarantee a value from a specific point in time.

Examples:

# Get any message sample
L::logs:(any(message)) [1h] BY service

# Get any error stack
L::error_logs:(any(stack_trace)) [1h] BY error_type

SHIFT

The expression-level SHIFT references the aggregate value from a specified duration ago, allowing current values and historical values to be compared in the same result:

Syntax:

<aggregate-expression> SHIFT <duration>

Current values, historical values, and derived calculations are all explicitly provided by projection expressions. To reference the same historical value multiple times, repeat the same SHIFT expression:

Parameters:

Parameter Type, requirements, and meaning
aggregate-expression Required; an expression that returns a fixed aggregation result for each window and each group, such as count(*) or sum(bytes), or such an aggregate column output by a subquery
duration Required; a positive fixed duration, such as 1h or 7d

Return value: Historical aggregate values aligned with the current result time and grouping.

Examples:

# Return the current count and the count for the same window seven days ago in the same result
L::logs:(count(*) AS current_count, count(*) SHIFT 7d AS previous_count) [1h::5m] BY service

# Calculate the ratio of the current value to the historical value, handling null or zero historical values
L::logs:(
  service,
  count(*) AS requests,
  count(*) SHIFT 7d AS requests_last_week,
  CASE
    WHEN (count(*) SHIFT 7d) = nil OR (count(*) SHIFT 7d) = 0 THEN nil
    ELSE count(*) / (count(*) SHIFT 7d)
  END AS requests_ratio
)[1d:1h] BY service

Usage limits:

  • It can appear only in projections and can act only on aggregate expressions in the current projection whose row identity is stable across windows, or on subquery measures with such an aggregation source.
  • It cannot act on projection aliases just declared in the same SELECT, dimension columns, WHERE, BY, HAVING, ORDER BY, or SORDER BY, and SHIFT cannot be nested.
  • Aggregations whose output rows are determined by the data in each window, such as distinct, distinct_by_collapse, field_values, and histogram, cannot be used as operands. Expressions that only transform raw fields, such as uint(field), are not aggregate measures; scalar transformations that wrap stable aggregations, such as abs(sum(field)), can be used.
  • To filter or sort based on historical values, do so in the outer SELECT.
  • All expression-level SHIFT instances in the same SELECT can contain at most 16 different offsets in total.

Query-level SHIFT (see Time Shift in the DQL main document) and expression-level SHIFT can be combined: the query-level offset first determines the baseline window for the entire query, and the expression-level offset then reads earlier aggregate values relative to that baseline window.


spread

Calculates the range (the difference between the maximum and minimum values).

Syntax:

spread(field)

Parameters:

  • field: Numeric field

Examples:

# Calculate the fluctuation range of response time
M::response_time:(spread(duration)) [1h] BY endpoint

stddev

Calculates the standard deviation.

Syntax:

stddev(field)

Parameters:

  • field: Numeric field

Examples:

# Calculate the standard deviation of response time
M::response_time:(stddev(duration)) [1h] BY endpoint

mode

Calculates the mode (the value that appears most frequently).

Syntax:

mode(field)

Parameters:

  • field: Any field

Return value: The mode; the type is determined by the input value.

Examples:

# Find the most common response status code
M::http:(mode(status)) [1h] BY endpoint

count_series

Calculates the number of independent raw time series involved in the query, not the number of groups in the statistical result.

Syntax:

count_series(field)

Parameters:

  • field: Any field (usually * or any existing field)

Time series are distinguished by the metric and label combination. For example, if the same host reports metrics for two CPU cores separately, this forms two time series; when grouped by host, that host still corresponds to only one group. To estimate the number of distinct host names, use count_distinct(host).

Return value: Number of time series.

Examples:

# Count the number of raw time series for the CPU metric
M::cpu:(count_series(*)) [1h]

# Count the number of raw time series for each service
M::http_requests:(count_series(*)) [1h] BY service

Statistical Aggregations (Estimation Functions)

The following functions use probabilistic data structures for estimation. They are suitable for large data volumes and can balance accuracy and performance.

count_distinct

Calculates the number of distinct values in a field (estimated value).

Syntax:

count_distinct(field)

Parameters:

  • field: Any field

Algorithm description:

Uses the HyperLogLog algorithm for cardinality estimation:

  • Number of registers: 2¹⁶ = 65536
  • Uses the LogLog-Beta estimation method
  • Standard error: approximately 0.4%

Use cases:

  • Count unique users (UV)
  • Calculate the number of distinct IP addresses
  • Analyze the number of unique request IDs

Examples:

# Count unique users
L::access_logs:(count_distinct(user_id)) [1d] BY service

# Count the number of distinct IP addresses accessed
L::nginx:(count_distinct(client_ip)) [1h] BY endpoint

percentile

Calculates the percentile of a field (estimated value).

Syntax:

percentile(field, n)
pXX(field)  // Shorthand form

Parameters:

  • field: Numeric field
  • n: Percentile, range 0-100

Shorthand forms:

  • p50(field) is equivalent to percentile(field, 50)
  • p95(field) is equivalent to percentile(field, 95)
  • p99(field) is equivalent to percentile(field, 99)

The percentile parameter of percentile(field, 95) is 95, while the quantile ratio of histogram_quantile(field, 0.95) is 0.95. The former takes ordinary numeric samples as input, while the latter takes histogram counts with bucket labels as input; the two cannot be directly substituted for each other.

Algorithm description:

Uses a log-linear interpolation histogram for estimation:

  • Bucket range: 10⁻⁹ to 10¹⁸, covering the vast majority of numeric scenarios
  • Each order of magnitude is divided into 128 buckets
  • Uses linear interpolation in log space to improve accuracy

Use cases:

  • Calculate P99 and P95 of response time
  • Analyze tail latency of performance metrics
  • Evaluate service level agreement (SLA) attainment

Examples:

# Calculate P99 of response time
M::response_time:(percentile(duration, 99)) [1h] BY service

# Use the shorthand form
M::response_time:(p99(duration)) [1h] BY service

# Call as a Rollup function: first calculate P95 on each time series, then aggregate by service
M::response_time:(avg(duration)) [1h::5m:percentile(95)] BY service

# Calculate multiple percentiles at the same time
M::response_time:(p50(duration), p95(duration), p99(duration)) [1h] BY service

median

Calculates the median, equivalent to percentile(field, 50).

Syntax:

median(field)

Parameters:

Parameter Type, requirements, and meaning
field Required; numeric field or numeric expression

Examples:

# Calculate the median response time
M::response_time:(median(duration)) [1h] BY service

Histogram Functions

DQL provides three histogram-related functions for different data sources and scenarios:

Function Use case Data source type Recommendation
histogram_auto Numeric distribution statistics for detail data such as logs and traces Detail model (Logs/Traces) ⭐⭐⭐ Recommended
histogram Histograms that require fixed bucket boundaries Detail model (Logs/Traces) ⭐⭐ Deprecated
histogram_quantile Calculate quantiles from Prometheus histogram metrics Prometheus metrics ⭐⭐⭐ Recommended

Automatically generates a distribution histogram and is designed for numeric distribution statistics of detail data such as logs and traces.

Features:

  • No need to specify bucket boundaries; automatically adapts to the data distribution
  • Uses a log-linear interpolation histogram algorithm, covering the numeric range from 10⁻⁹ to 10¹⁸
  • Returns both percentile statistics and bucket distribution information

Syntax:

histogram_auto(field)

Parameters:

  • field: Numeric field

Return value:

Column name Description
lower_bounds Array of lower bounds for each bucket
upper_bounds Array of upper bounds for each bucket
counts Array of counts for each bucket
min Minimum value
p50 Median
p75 75th percentile
p90 90th percentile
p95 95th percentile
p99 99th percentile
max Maximum value

Algorithm description: Uses an estimated histogram (log-linear interpolation), with each order of magnitude divided into 128 buckets. It is suitable for distribution statistics on large data volumes.

Use cases:

  • Analyze response time distribution in logs
  • Analyze elapsed time distribution in traces
  • Exploratory data analysis without preset bucket boundaries

Examples:

# Analyze the response time distribution of Nginx access logs
L::nginx:(histogram_auto(response_time)) [1h]

# Analyze request duration distribution by service
L::app_logs:(histogram_auto(duration)) [1h] BY service

# Analyze the elapsed time distribution of trace calls
T::http_client:(histogram_auto(elapsed)) [1h] BY operation

Example result:

lower_bounds upper_bounds counts min p50 p75 p90 p95 p99 max
[0, 10, 100, 1000] [10, 100, 1000, 10000] [1000, 500, 99, 1] 0.5 8 46 80 280 850 1200

This table is a simplified structural illustration for readability and is not an actual query return; actual bucket boundaries are generated by the engine. The three arrays correspond to the same bucket by the same index. For example, the first bucket has a lower bound of 0, an upper bound of 10, and a count of 1000. Percentiles and extrema describe the same batch of data and cannot be independently combined.


histogram (Deprecated)

Generates a histogram with specified bucket boundaries. This function is Deprecated; histogram_auto is recommended instead.

Description: histogram requires manually specifying bucket boundary parameters, which makes it less flexible. histogram_auto can automatically adapt to the data distribution, cover a wider numeric range, and return richer statistical information.

Syntax:

histogram(field, left_bound, right_bound, bucket_size [, threshold])

Parameters:

  • field: Numeric field
  • left_bound: Left boundary
  • right_bound: Right boundary
  • bucket_size: Bucket size
  • threshold (optional): Minimum count per bucket; buckets below this value are not returned

Return value: Returns two columns: bucket_le (bucket upper boundary) and count (count).

Examples:

# Generate a histogram in the range 0-1000ms with one bucket every 100ms
M::response_time:(histogram(duration, 0, 1000, 100)) [1h]

# histogram_auto is recommended instead
M::response_time:(histogram_auto(duration)) [1h]

Example result:

bucket_le count
100 1500
200 2800
300 3500
... ...
1000 5000

histogram_quantile

Calculates quantiles from Prometheus histogram metrics.

Features:

  • Specifically designed for histogram-type metrics reported by Prometheus
  • Relies on the le label (or VictoriaMetrics' vmrange label) to identify bucket boundaries
  • Input data should be cumulative counts

Syntax:

histogram_quantile(field, q)

Parameters:

  • field: Numeric field storing bucket counts; examples in this section use the duration_bucket field in the http_request_duration measurement
  • q: Quantile, range 0-1 (for example, 0.99 means P99)

Return value: Quantile value; the unit is determined by the unit of the bucket boundaries.

Minimal query:

M::http_request_duration:(histogram_quantile(duration_bucket, 0.95) AS p95_duration) [1h] BY service

Use case comparison:

Scenario Recommended function Description
Analyze response time distribution in logs histogram_auto Logs are detail data and do not have pre-aggregated histograms
Analyze P99 of Prometheus histogram metrics histogram_quantile Metrics are already pre-aggregated by the le label
Analyze elapsed time distribution of trace calls histogram_auto Traces are detail data

le label handling mechanism:

histogram_quantile relies on the le label (less than or equal) to identify histogram bucket boundaries:

  1. Prometheus format (default): Uses the le label directly to represent the bucket upper boundary
  2. The le value is numeric (such as "0.1", "1", "10") or "+Inf" (infinity)
  3. Data should be cumulative counts

  4. VictoriaMetrics format: Uses the vmrange label to represent ranges

  5. The format is "lower...upper" (such as "0.1...0.2")
  6. Data is range counts (non-cumulative)
  7. The function automatically converts range counts to cumulative counts

Calculation process:

  1. Sort all buckets by le value
  2. If the format is vmrange, accumulate counts to convert them into a cumulative distribution
  3. Ensure bucket counts are monotonically increasing (fix possible anomalous data)
  4. Use linear interpolation to calculate the target quantile

Differences from PromQL:

Feature DQL PromQL
Function type Aggregation function Transformation function
Input data Directly reads metrics with the le label Often used with sum(rate(...)) by (le)
Usage histogram_quantile(field, 0.99) histogram_quantile(0.99, sum(rate(...)) by (le))
Data format Supports both le and vmrange labels Supports only the le label
Grouping Through the DQL BY clause Explicit grouping through by (le)

Syntax comparison:

The following comparison targets classic bucket histograms and is used to compare parameter order and grouping. Before comparing numeric results, cumulative counts, delta or rate definitions, time windows, and groupings must be aligned. DQL and PromQL queries that have not undergone the same preprocessing cannot be considered numerically equivalent.

This section assumes that the DQL measurement is http_request_duration, the bucket count field is duration_bucket, and it contains the le label (such as 0.1, 0.5, 1, 5, +Inf) and the service label. The metric name in the PromQL comparison is http_request_duration_bucket; these two names represent how data is organized in the respective query languages in this example and are not a general automatic mapping rule.

Scenario 1: Calculate P99 latency

DQL:

M::http_request_duration:(histogram_quantile(duration_bucket, 0.99)) [1h] BY service

Corresponding PromQL syntax:

histogram_quantile(0.99, sum(rate(http_request_duration_bucket[1h])) by (le, service))

Scenario 2: Calculate P95 latency for each service (multiple groups)

DQL:

M::http_request_duration:(
    histogram_quantile(duration_bucket, 0.95)
) [1h] BY service, endpoint

Corresponding PromQL syntax:

histogram_quantile(0.95, sum(rate(http_request_duration_bucket[1h])) by (le, service, endpoint))

Scenario 3: Calculate P50 (median) and P99

DQL:

M::http_request_duration:(
    histogram_quantile(duration_bucket, 0.50) as p50,
    histogram_quantile(duration_bucket, 0.99) as p99
) [1h] BY service

Corresponding PromQL syntax:

label_join(
  histogram_quantile(0.50, sum(rate(http_request_duration_bucket[1h])) by (le, service)), "quantile", "", "0.50"
)
or
label_join(
  histogram_quantile(0.99, sum(rate(http_request_duration_bucket[1h])) by (le, service)), "quantile", "", "0.99"
)

Note: PromQL requires label_join or label_replace to distinguish results for different quantiles.

Notes:

  • Input data must contain the le or vmrange label; otherwise, calculation is impossible.
  • If there is no +Inf bucket, the upper boundary of the last bucket is used as the maximum value.
  • Buckets with a count of 0 or NaN are skipped.
  • When the quantile is < 0, -Inf is returned; when it is > 1, +Inf is returned.

TopN Functions

top

Gets the top N largest values.

It returns the larger values within the current grouping and time window; it does not mean selecting the top N groups by host or service. To rank groups, use SORDER BY with SLIMIT.

Syntax:

top(field, n)

Parameters:

  • field: Numeric field
  • n: Number of values to return

Return value: A multi-row result, where each row contains one selected value; if there are insufficient records, fewer than n values are returned.

Examples:

# Get the 5 requests with the longest response time
M::response_time:(top(duration, 5)) [1h] BY service

# Get the 10 largest traffic values
M::network:(top(bytes, 10)) [1h]

Example result:

service top(duration, 5)
api 1250
api 1180
api 1050
api 980
api 920

Note: Multiple rows are returned, each containing one TopN value.


bottom

Gets the top N smallest values.

It returns the smaller values within the current grouping and time window; it does not mean selecting the top N groups. To rank groups, use SORDER BY with SLIMIT.

Syntax:

bottom(field, n)

Parameters:

  • field: Numeric field
  • n: Number of values to return

Return value: A multi-row result, where each row contains one selected value; if there are insufficient records, fewer than n values are returned.

Examples:

# Get the 5 requests with the shortest response time
M::response_time:(bottom(duration, 5)) [1h] BY service

Example result:

service bottom(duration, 5)
api 12
api 18
api 25
api 32
api 45

Note: Multiple rows are returned, each containing one BottomN value.


Value Collection Functions

distinct

Returns all distinct values of a field.

Syntax:

distinct(field)

Parameters:

Parameter Type, requirements, and meaning
field Required; field or expression to process

Return value: Multiple rows, each being a distinct value.

Examples:

# Get all distinct status codes
M::http:(distinct(status)) [1h] BY endpoint

Example result:

endpoint distinct(status)
/api/v1 200
/api/v1 404
/api/v1 500
/health 200

Note: Multiple rows are returned, each containing one distinct value.


distinct_by_collapse

Gets distinct values of a field according to a collapse policy, retaining the last value of other fields during deduplication.

Syntax:

distinct_by_collapse(field, [last_field1, last_field2, ...])

Parameters:

  • field: Field used as the deduplication key
  • last_fields (optional): List of fields whose last values should be retained

Description: Unlike distinct, distinct_by_collapse retains information from other related fields during deduplication (taking the last value), making it suitable for scenarios that need to preserve context information.

Return value: A multi-row result formed by the deduplication key, with explicitly specified retained fields attached.

Examples:

# Get distinct user IDs and retain the last access time and path for each user
L::access_logs:(distinct_by_collapse(user_id, [timestamp, path])) [1h]

# Get distinct hosts and retain the last status and message
O::HOST:(distinct_by_collapse(host, [status, message])) [1h]

Example result:

user_id last(timestamp) last(path)
user001 1704067200000 /checkout
user002 1704067100000 /product
user003 1704067000000 /home

Note: Returns the deduplicated primary field value and the last values of other fields specified by last_fields.


collect

Collects all values (including duplicates).

Syntax:

collect(field [, limit])

Parameters:

  • field: Any field
  • limit (optional): Maximum number to collect

Return value: An array; the array contents are still subject to the resource limits of the query and engine.

Examples:

# Collect all response times
M::response_time:(collect(duration)) [1h] BY service

# Collect at most 100 values
M::response_time:(collect(duration, 100)) [1h] BY service

Example result:

service collect(duration)
api [120, 135, 98, 142, ...]
web [45, 52, 48, 61, ...]

Note: Returns an array type containing all collected values (which may include duplicate values).


collect_distinct

Collects all distinct values.

Syntax:

collect_distinct(field [, limit])

Parameters:

  • field: Any field
  • limit (optional): Maximum number to collect

Return value: An array of deduplicated values.

Examples:

# Collect all distinct error types
L::error_logs:(collect_distinct(error_type)) [1h] BY service

Example result:

service collect_distinct(error_type)
api ["timeout", "connection refused", "404"]
web ["200", "301", "404"]

Note: Returns an array type containing all deduplicated values.


field_values

Gets all values of a field and returns an array type.

Syntax:

field_values(field)

Parameters:

Parameter Type, requirements, and meaning
field Required; field or expression to process

Return value: Array of field values.

Examples:

# Get all tag values
M::metrics:(field_values(tags)) [1h] BY metric_name

Example result:

metric_name field_values(tags)
cpu_usage ["host:A", "env:prod", "team:backend"]
memory_used ["host:B", "env:staging", "team:frontend"]

Note: Returns an array type containing all values of the field.


Filtered Aggregations

count_filter

Counts field values that are in the specified list.

Syntax:

count_filter(field, [value1, value2, ...])

Parameters:

  • field: Any field
  • values: List of values

Return value: Integer conditional count; other records in the same group can still participate in other aggregations.

Examples:

# Count requests with specific status codes
M::http:(count_filter(status, [200, 201, 204])) [1h] BY endpoint

# Count error-level logs
L::logs:(count_filter(level, ["error", "critical"])) [1h] BY service

Helper Functions

default

Sets a default value for a field and returns the default value when the field is empty.

default is a null fallback for a field or expression. It is not an aggregation function and does not generate missing time windows. 0 and the empty string are themselves values; for filling query result series, see fill.

Syntax:

default(field, default_value)

Parameters:

  • field: Any field
  • default_value: Default value (can be a number, string, boolean, or null)

Return value: The non-null input value, or the fallback value when the input is nil.

Examples:

# Set a default response time for null values
M::response_time:(default(duration, 0)) [1h] BY service

Time Series Functions

Time series functions are used to process data that changes over time, especially Counter-type metrics.

Rollup Functions

Rollup functions are used to preprocess raw time series data within a time window. For detailed information, see Rollup Functions in this document.

Syntax notes:

  • Rollups are written in the time clause, such as [rate] or [1h::5m:rate].
  • Writing outside the query, such as rate(DQL), is an outer function, not a Rollup.
  • For differences in execution stage and parameters among Rollup shorthand, Rollup function calls, and explicit aggregation calls, see Rollup Functions in the DQL main document.

The time clause supports Rollup shorthand and also supports passing additional algorithm parameters to Rollup functions, such as [1h::1m:ewma(0.3)]. Parameters in the time clause represent only algorithm parameters; the input field is still determined by the Select field. Functions that require multiple input fields should use explicit aggregation calls in the Select clause.

Functions that support Rollup shorthand:

Function Description
rate Calculate growth rate (per second)
irate Calculate instantaneous growth rate
increase Calculate increase
deriv Calculate derivative (rate of change)
difference Calculate difference
non_negative_derivative Calculate non-negative derivative
non_negative_difference Calculate non-negative difference
rate_over_sum Calculate average per second
rate_over_count Calculate count per second
sum Sum
avg Average
min Minimum
max Maximum
count Count
first First value
last Last value
stddev Standard deviation
mode Mode
spread Range
any Any value
slope Linear trend slope
zscore Z-Score of the latest point
mad_score MAD anomaly score of the latest point
change_score Series change score

Functions that support Rollup function calls:

Function Description
ewma(alpha) Exponentially weighted moving average
moving_average(n) Moving average
percentile(p) Percentile

Examples:

# Calculate request QPS
M::http_requests:(sum(request_count)) [1h::5m:rate] BY service

# Shorthand form: request_count is a cumulative Counter
M::http_requests:(sum(request_count)) [rate] BY service

# Rollup function call with algorithm parameters
M::cpu:(avg(usage)) [1h::1m:ewma(0.3)] BY host

Growth Rate Calculation

rate

Calculates the growth rate of a metric (per second).

Syntax:

rate(field)

Description: rate calculates the average growth rate of a Counter metric within a time window. Counters report cumulative readings; when calculating rates, process the growth of each raw time series first, then aggregate by dimensions such as service. Do not treat the sum of cumulative readings as a request rate.

Use cases:

  • Calculate request QPS
  • Calculate data write rate
  • Analyze traffic growth trends

Parameters:

Parameter Type, requirements, and meaning
field Required; numeric field or numeric expression

Return value: Numeric rate, in input unit per second.

Examples:

# In-query call: explicitly specify the Counter field
M::http_requests:(rate(request_count)) [1h::5m] BY service

# Rollup: first calculate the rate for each raw time series, then sum by service
M::http_requests:(sum(request_count)) [1h::5m:rate] BY service

# Calculate the data write rate
M::data_ingestion:(sum(bytes)) [rate] BY source

irate

Calculates the instantaneous growth rate of a metric.

Syntax:

irate(field)

Description: Unlike the window statistics of rate, irate uses the last two valid points to calculate the instantaneous growth rate, making it more sensitive to short-term fluctuations. When comparing these two functions, keep the field, time range, and grouping the same.

Parameters:

Parameter Type, requirements, and meaning
field Required; numeric field or numeric expression

Return value: Numeric rate, in input unit per second.

Examples:

# In-query call: calculate the instantaneous rate for the specified Counter field
M::http_requests:(irate(request_count)) [1h::5m] BY service

# Rollup: first calculate separately for each raw time series, then sum by service
M::http_requests:(sum(request_count)) [1h::5m:irate] BY service

increase

Calculates the increase of a metric.

Syntax:

increase(field)

Description: increase calculates the increase of a Counter within a time window without dividing by time. For example, if no reset occurs and the count grows from 100 to 130, the increase is 30; adding up the cumulative readings during the period is not the increase.

Parameters:

Parameter Type, requirements, and meaning
field Required; numeric field or numeric expression

Examples:

# In-query call: calculate the increase of the specified Counter field within the window
M::http_requests:(increase(request_count)) [1h::5m] BY service

# Rollup: first calculate the increase for each raw time series, then sum by service
M::http_requests:(sum(request_count)) [1h::5m:increase] BY service

rate_over_sum

Calculates the average value per second (sum / number of seconds in the time window).

Syntax:

rate_over_sum(field)

Description: Equivalent to sum(field) / time window (seconds), suitable for data where each record is an independent increment. For example, if each log record records the number of bytes transferred by that request, you can first sum them and then divide by the number of seconds in the window to get the average bytes per second. Multiple readings of a cumulative Counter cannot be directly added and treated as an increase; use rate for such data.

Difference from rate:

  • rate: Calculates the growth rate of a Counter (handles resets)
  • rate_over_sum: Simply divides sum by the number of seconds in the time window

Parameters:

Parameter Type, requirements, and meaning
field Required; numeric field or numeric expression

Return value: Rate per second, that is, sum(field) / window seconds.

Examples:

# bytes indicates the number of bytes transferred by each log record
L::access_logs:(rate_over_sum(bytes) AS bytes_per_second) [1h::1m] BY service

rate_over_count

Calculates the count per second (count / number of seconds in the time window).

Syntax:

rate_over_count(field)

Description: Equivalent to count(field) / time window (seconds), used to calculate the number of occurrences per second.

Parameters:

Parameter Type, requirements, and meaning
field Required; when a field is specified, count by that field; when using *, count records

Return value: Average number of occurrences per second.

Examples:

# Calculate the number of error logs per second
L::error_logs:(rate_over_count(*)) [1h] BY error_type

Difference Calculation

This section describes function semantics. The same function can be used as a Rollup (such as [rate], [increase]) or written in an in-query expression (such as rate(field), increase(field)); the execution stages differ, so choose the location based on business requirements first.

rate / deriv

Calculates the rate of change (derivative). rate is used for Counter-type metrics (ignores negative values), and deriv is used for Gauge-type metrics (retains negative values).

Aliases: The alias of rate is non_negative_derivative; the alias of deriv is derivative (PromQL style).

Compatible names can also be written in complete queries:

Name Complete query example
derivative M::memory:(derivative(used)) [1h::5m] BY host
non_negative_derivative M::requests:(non_negative_derivative(total)) [1h::5m] BY service
non_negative_difference M::requests:(non_negative_difference(total)) [1h::5m] BY service

Syntax:

// Counter metric: calculate non-negative rate of change (ignore negative values caused by resets)
rate(field)

// Gauge metric: calculate the full rate of change (including negative values)
deriv(field)

Function selection:

Function Description Use case
rate Calculates only non-negative rate of change Counter-type metrics (monotonically increasing)
deriv Calculates the full rate of change (including negative values) Gauge-type metrics (can increase or decrease)

Parameters:

Parameter Type, requirements, and meaning
field Required; numeric field or numeric expression

Return value: rate: numeric rate, in input unit per second; deriv: numeric rate of change, in input unit per second, which can be negative.

Examples:

# Counter metric: calculate request QPS
M::requests:(rate(count)) [1h::5m] BY service

# Gauge metric: calculate the rate of change in memory usage
M::memory:(deriv(used)) [1h::5m] BY host

increase / difference

increase calculates the increase of a Counter within a window; difference calculates the difference between adjacent values of a Gauge and retains negative values. Do not confuse the total increase within a window with the difference between a pair of adjacent values.

Description: increase and difference are two independent functions with different behaviors; they are not aliases.

Syntax:

// Counter metric: calculate increase within the window
increase(field)

// Gauge metric: calculate the full difference (including negative values)
difference(field)

Function selection:

Function Description Use case
increase Calculate the Counter increase within the window Counter-type metrics
difference Calculate the difference between adjacent values, including negative values Gauge-type metrics (can increase or decrease)

Parameters:

Parameter Type, requirements, and meaning
field Required; numeric field or numeric expression

Examples:

# Counter metric: calculate request increase
M::requests:(increase(count)) [1h::5m] BY service

# Gauge metric: calculate request count changes (may increase or decrease)
M::requests:(difference(count)) [1h::5m] BY service

Moving Calculations

moving_average

Calculates the moving average.

Syntax:

moving_average(field, n)

Parameters:

  • field: Numeric field
  • n: Number of data points for the moving average, not minutes or seconds

An in-query call passes the field explicitly; a Rollup processes each raw time series before entering grouped aggregation. The outer moving_average(DQL_expression, n) processes result points already output by the query. For example, when the inner layer aggregates by one minute, outer n=5 means using five aggregate result points; changing the inner step also changes the time range corresponding to these five points.

Examples:

# Calculate a 5-point moving average
M::cpu:(moving_average(usage, 5)) [1h::1m] BY host

# Call as a Rollup function: first apply a 5-point moving average to each time series, then aggregate by host
M::cpu:(avg(usage)) [1h::1m:moving_average(5)] BY host

Time Series Analysis Aggregations

The following functions are used as aggregation functions within a query and calculate one numeric result for the numeric sequence in each time window and group.

ewma

Calculates the exponentially weighted moving average (EWMA). alpha is the smoothing coefficient and must be explicitly passed.

Syntax:

ewma(field, alpha)

Parameters:

  • field: Numeric field
  • alpha: Smoothing coefficient, range (0, 1]; the larger the value, the higher the weight of the latest data point

Description:

  • ewma has no implicit default alpha; ewma(field) reports an error.
  • When used as a Rollup in the time clause, write it as [...:ewma(alpha)]; parameters in the time clause pass only alpha, not the field name.
  • Because ewma requires alpha, the parameterless Rollup shorthand [...:ewma] is not supported.

Return value: Exponentially weighted smoothed value.

Examples:

# Explicit aggregation call: calculate EWMA during the Select aggregation stage
M::cpu:(ewma(usage, 0.3)) [1h::1m] BY host

# Rollup function call: first calculate EWMA for each time series, then aggregate by host
M::cpu:(avg(usage)) [1h::1m:ewma(0.3)] BY host

slope

Calculates the slope of the linear trend of a series over time.

Syntax:

slope(field)

Description:

  • At least 2 valid points are required.
  • Returns a null value when time does not change or there are insufficient valid points.

Parameters:

Parameter Type, requirements, and meaning
field Required; numeric field or numeric expression

Return value: Trend slope, in input unit per second.

Examples:

# Calculate the growth trend of memory usage
M::memory:(slope(used)) [1h::5m] BY host

zscore

Calculates the Z-Score of the latest point relative to the mean and standard deviation within the window.

Syntax:

zscore(field)

Description:

  • The result is (latest - mean) / stddev.
  • At least 2 valid points are required; returns a null value when the standard deviation is 0.

Parameters:

Parameter Type, requirements, and meaning
field Required; numeric field or numeric expression

A positive value indicates that the latest point is above the window mean, and a negative value indicates that it is below the window mean. The result is a deviation score, not an anomaly probability.

Examples:

# Evaluate the deviation of the latest response time relative to the historical window
M::response_time:(zscore(duration)) [1h::5m] BY service

mad_score

Calculates the MAD (Median Absolute Deviation) anomaly score of the latest point.

Syntax:

mad_score(field)

Description:

  • Uses the median and MAD to measure the deviation of the latest point, which is more robust to extreme values than mean/standard deviation.
  • At least 2 valid points are required; returns a null value when MAD is 0.

Parameters:

Parameter Type, requirements, and meaning
field Required; numeric field or numeric expression

Examples:

# Use a robust anomaly score to detect the latest latency point
M::latency:(mad_score(p95)) [1h::5m] BY service

change_score

Calculates the change score of a series within a window, used to detect time series where the mean shifts significantly.

Syntax:

change_score(field)

Description:

  • Enumerates possible split points, compares the mean difference between the left and right segments around the split point, and normalizes by the pooled standard deviation.
  • At least 4 valid points are required; returns a null value when there are insufficient valid points.

Parameters:

Parameter Type, requirements, and meaning
field Required; numeric field or numeric expression

It focuses on changes between the two segments before and after the window; zscore and mad_score focus on the deviation of the latest point relative to other data in the window. The meanings of these two types of scores are different.

Examples:

# Detect whether the error rate changes abruptly within the window
M::error_rate:(change_score(value)) [1h::5m] BY service

corr

Calculates the Pearson correlation coefficient between two numeric fields.

Syntax:

corr(left_field, right_field)

Description:

  • The return value range is usually [-1, 1].
  • At least 2 valid point pairs are required; returns a null value when either field has no variation.
  • corr requires two input fields and does not support time clause Rollup syntax.

Parameters:

Parameter Type, requirements, and meaning
left_field Required; first numeric field
right_field Required; second numeric field, forming valid numeric pairs with the former

A value close to 1 indicates positive linear correlation, close to -1 indicates negative linear correlation; close to 0 indicates weak linear correlation, which does not mean the two are completely unrelated.

Examples:

# Calculate the correlation between CPU usage and request volume
M::service_metric:(corr(cpu_usage, request_count)) [1h::5m] BY service

cumsum

Calculates the cumulative sum.

Syntax:

cumsum(DQL_expression)

Parameters:

Parameter Type, requirements, and meaning
query Required; complete DQL query whose output is processed by the outer function

Return value: A cumulative value sequence corresponding to each time point.

Examples:

# First count logs in each window, then accumulate the result point by point
cumsum(L::logs:(count(*)) [1h::5m] BY service)

Transformation Functions

Transformation functions are used for mathematical operations, type conversion, or string processing on field values.

Mathematical Functions

abs

Calculates the absolute value.

Syntax:

abs(field)

Parameters:

Parameter Type, requirements, and meaning
field Required; numeric field or numeric expression

Examples:

# Calculate the absolute value of temperature deviation
M::temperature:(abs(deviation)) [1h] BY sensor

round / ceil / floor

Rounding functions.

Syntax:

round(field)          // Round to an integer
round(field, digits)  // Round to the specified number of decimal places
ceil(field)           // Round up
floor(field)          // Round down

Parameters:

Parameter Type, requirements, and meaning
field Required; numeric field or numeric expression
digits Optional; number of decimal places to retain; if omitted, round to an integer

When digits is not passed, the three rounding methods can be distinguished by the following values. ceil rounds toward positive infinity, and floor rounds toward negative infinity, so the results for negative numbers also differ:

Input round ceil floor
1.2 1 2 1
-1.2 -1 -1 -2

Examples:

# Round response time up
M::response_time:(ceil(duration)) [1h]

# Round a percentage
M::cpu:(round(usage)) [1h] BY host

# Retain 2 decimal places for average response time
L::log:(round(avg(duration), 2)) BY api

log / log2 / log10

Logarithmic functions.

Syntax:

log(field)    // Natural logarithm
log2(field)   // Base 2
log10(field)  // Base 10

Parameters:

Parameter Type, requirements, and meaning
field Required; positive numeric field or expression

Return value: log: value after logarithmic transformation; log2: value after logarithmic transformation; log10: value after logarithmic transformation.

Examples:

# Calculate the value after logarithmic transformation
M::metrics:(log(value)) [1h] BY metric_name

Type Conversion

int / uint / float / string / bool

Type conversion functions.

Syntax:

int(field)    // Convert to signed integer
uint(field)   // Convert to unsigned integer
float(field)  // Convert to floating point
string(field) // Convert to string
bool(field)   // Convert to boolean

Parameters:

Parameter Type, requirements, and meaning
field Required; field or expression to process

Return value: int: value of signed integer type; uint: value of unsigned integer type; float: value of floating-point type; string: value of string type; bool: value of boolean type.

Examples:

# Convert a string to a numeric value
L::logs:(int(response_time)) [1h] BY service

# Convert a numeric value to a string for concatenation
M::metrics:(string(value)) [1h] BY metric_name

String Functions

lower

Converts a string to lowercase.

Syntax:

lower(field)

Parameters:

  • field: String field

Return value: Returns the converted lowercase string.

Examples:

L::logs:(lower(service) AS normalized_service) [1h] LIMIT 10

upper

Converts a string to uppercase.

Syntax:

upper(field)

Parameters:

  • field: String field

Return value: Returns the converted uppercase string.

Examples:

L::logs:(upper(service) AS normalized_service) [1h] LIMIT 10

trim

Removes whitespace from both ends of a string.

Syntax:

trim(field)

Parameters:

  • field: String field

Return value: Returns the string with leading and trailing whitespace removed.

Examples:

L::logs:(trim(service) AS normalized_service) [1h] LIMIT 10

ltrim

Removes whitespace from the left side of a string.

Syntax:

ltrim(field)

Parameters:

  • field: String field

Return value: Returns the string with leading whitespace removed.

Examples:

L::logs:(ltrim(service) AS normalized_service) [1h] LIMIT 10

rtrim

Removes whitespace from the right side of a string.

Syntax:

rtrim(field)

Parameters:

  • field: String field

Return value: Returns the string with trailing whitespace removed.

Examples:

L::logs:(rtrim(service) AS normalized_service) [1h] LIMIT 10

length

Returns the string length (calculated by number of characters).

Syntax:

length(field)

Parameters:

  • field: String field

Return value: Returns the string length.

Examples:

L::logs:(length(message) AS message_length) [1h] LIMIT 10

substr

Extracts a substring.

Syntax:

substr(field, start)
substr(field, start, length)

Parameters:

  • field: String field
  • start: Start position (starting from 0; negative numbers indicate starting from the end)
  • length (optional): Substring length

Return value: Returns the extracted substring.

Examples:

# Extract the first 10 characters of the message
L::logs:(substr(message, 0, 10)) [1h]

# Extract the last 5 characters
L::logs:(substr(message, -5)) [1h]

Example result:

message substr(message, 0, 10) substr(message, -5)
"Error: connection timeout" "Error: con" "meout"

regexp_extract

Regular expression extraction.

Syntax:

regexp_extract(field, pattern)
regexp_extract(field, pattern, n)

Parameters:

  • field: String field
  • pattern: Regular expression
  • n (optional): Extract the nth capture group; default is 0 (entire match)

Return value: Returns a single string containing the content of the nth capture group. Returns null if there is no match.

Examples:

# Extract error codes
L::logs:(regexp_extract(message, 'error_code: (\d+)', 1)) [1h]

# Extract IP addresses
L::nginx:(regexp_extract(message, '(\d+\.\d+\.\d+\.\d+)', 1)) [1h]

Example result:

service regexp_extract(message, 'error_code: (\d+)', 1)
api "404"
api "500"
web null

regexp_extract_all

Extracts all matching results.

Syntax:

regexp_extract_all(field, pattern)
regexp_extract_all(field, pattern, n)

Return value: Returns an array of strings containing all matching substrings.

Parameters:

Parameter Type, requirements, and meaning
field Required; string field or string expression
pattern Required; regular expression string
n Optional; capture group number, where 0 means the entire match

Examples:

# Extract all numbers
L::logs:(regexp_extract_all(message, '\d+', 0)) [1h]

# Extract all IP addresses
L::logs:(regexp_extract_all(message, '\d+\.\d+\.\d+\.\d+', 0)) [1h]

Example result:

message regexp_extract_all(message, '\d+.\d+.\d+.\d+', 0)
Request from 192.168.1.1 to 10.0.0.1 ["192.168.1.1", "10.0.0.1"]

regexp_replace

Replaces matched text using a regular expression.

Syntax:

regexp_replace(field, pattern, replacement)

Parameters:

  • field: String field
  • pattern: Regular expression
  • replacement: Replacement string; use $1, ${1}, $2, etc. to reference capture groups; when a capture group is immediately followed by a letter, digit, or underscore, use ${1} to disambiguate (for example, ${1}_suffix); use $$ to output a literal $

Return value: Returns the replaced string. If there is no match, returns the original string.

Examples:

# Remove numbers from messages and aggregate by prefix
L::logs:(substr(regexp_replace(message, '\\d+', ''), 0, 20) AS prefix, count(*)) [1h] BY prefix

# Normalize user IDs using capture groups
L::logs:(regexp_replace(message, 'user=([0-9]+)', 'uid=$1') AS normalized) [1h]

md5

Calculates the MD5 hash value.

Syntax:

md5(field)

Return value: Returns a 32-character hexadecimal string (lowercase).

Parameters:

Parameter Type, requirements, and meaning
field Required; string field or string expression

Examples:

# Calculate the MD5 of the message
L::logs:(md5(message)) [1h]

Example result:

service md5(message)
api 5d41402abc4b2a76b9719d911017c592
web 098f6bcd4621d373cade4e832627b4f6

concat

String concatenation.

Syntax:

concat(field, ...)

Return value: Returns a single concatenated string.

Parameters:

Parameter Type, requirements, and meaning
value1, value2, ... Required values to concatenate; it is recommended to explicitly provide strings, converting other types with string first

Examples:

# Concatenate multiple fields
L::logs:(concat(service, ":", level)) [1h]

# Result: "api:error", "web:info", etc.

Example result:

service level concat(service, ":", level)
api error "api:error"
web info "web:info"

set

Deduplicates and sorts an array field.

Syntax:

set(DQL_expression)

Return value: Returns the deduplicated and sorted array.

Parameters:

Parameter Type, requirements, and meaning
query Required; complete DQL query whose output is processed by the outer function

Examples:

# Get all distinct tags
set(M::metrics:(tags) [1h] BY metric_name)

# Deduplicate the result of collect
set(M::http:(collect(status)) [1h] BY endpoint)

Example result:

metric_name set(tags)
cpu_usage ["env:prod", "host:A", "team:backend"]
memory_used ["env:staging", "host:B", "team:frontend"]

Log Clustering

drain

Uses the Drain algorithm to group similar logs into the same cluster and returns a representative log sample for that cluster.

Syntax:

drain(field, similarity_threshold)
drain(field, similarity_threshold, max_clusters)

Parameters:

  • field: String field or string expression, usually message
  • similarity_threshold: Similarity threshold, range (0, 1]; the larger the value, the more similar logs must be to be grouped into the same cluster
  • max_clusters: Optional, maximum number of clusters, range [1, 10000]; defaults to 1000 when omitted

Return value:

Returns a string-type representative log sample. The sample is the original log when the cluster was created, not the generalized template maintained internally by Drain.

Algorithm description:

Drain is a log clustering algorithm based on a parse tree. The function continuously trains the clusterer during execution: when a new log matches an existing cluster, it returns the representative sample of that cluster; when it does not match, it creates a new cluster and uses the current log as the representative sample of that cluster.

Use cases:

  • Group and count similar logs
  • Cluster analysis of anomalous logs
  • Log noise reduction

Examples:

# Cluster and count similar logs with similarity 0.7 and a maximum of 1000 clusters
L::logs:(count(*)) [1h] BY drain(message, 0.7, 1000) AS sample

# When max_clusters is omitted, the default maximum is 1000 clusters
L::logs:(count(*)) [1h] BY drain(message, 0.9) AS sample

# You can also concatenate multiple fields before clustering
L::logs:(count(*)) [1h] BY drain(concat(service, " ", message), 0.7) AS sample

Example result:

sample count(*)
"Request from 192.168.1.1 to /api/users took 35 ms" 128
"Query SELECT * FROM orders executed in 18 ms" 42

Matching Functions

Matching functions are used for text matching in the WHERE clause and can also be used as expressions that return booleans.

Substring Matching

match

Checks whether a field contains the specified substring.

Syntax:

match(pattern)
match(field, pattern)

Parameters:

  • pattern: Substring to match
  • field: Field name (optional; can be omitted in the WHERE clause)

Return value: Boolean value, which can be placed in a WHERE condition.

Examples:

# Use in WHERE
L::logs:(message) {match(message, "error")} [1h]

# Shorthand form
L::logs:(message) {match("error")} [1h]

# Return the match result and name the result column match_result
L::logs:(message, match(message, "timeout") AS match_result) [1h] LIMIT 10

Phrase Matching

Tokenized phrase matching, supporting mixed Chinese and English.

Syntax:

search(query)
search(field, query)

Parameters:

  • query: Query phrase
  • field: Field name (optional)

Matching and tokenization rules:

  • English and numbers: Consecutive letters and numbers are merged into one term (Token), and case is ignored (for example, Error, error, and ERROR are all treated as the same term error, and http2 is treated as one term).
  • Chinese: Tokenized by common phrases or individual characters (for example, 连接超时 is split into 连接 and 超时).
  • Punctuation and separators: Spaces, tabs, newlines, and all common punctuation marks (including ., _, :, /, -, @, ?, =, &, etc.) are treated as word boundary separators. For example:
  • user_name is split into user and name
  • api.example.com is split into api, example, and com
  • host-01:8080 is split into host, 01, and 8080
  • Keyword matching (default): When the query string contains multiple terms (such as search("connection timeout")), the target text must contain all terms by default; the order or adjacency of terms is not required.
  • Phrase matching (#"..."): When the value starts with # and is wrapped in double quotes (such as #"build error"), phrase matching is used, requiring the tokenized terms to appear adjacent in order in the original text (only spaces or punctuation separators are allowed between terms); # and the double quotes at both ends are not part of the matching content.
  • Legacy double-quote syntax ("..."): Values that start and end with double quotes (such as "build error") still retain phrase matching semantics in Monitors (referer=func); in other query entry points, they are equivalent to keyword matching without quotes. It is recommended to use #"..." consistently.
  • Pure punctuation and special boundaries:
  • In the special quote forms above, if the value contains only whitespace or punctuation (no letters, numbers, or Chinese characters, such as #"---"), it degrades to matching by consecutive literal substring.
  • The empty query "" matches nothing.
  • Forms with only one double quote or with double quotes not at both ends are treated as ordinary tokenized search parameters and are not specially interpreted.
  • When to use match or re instead:
  • To strictly distinguish punctuation (for example, distinguish user_name from user-name, or match raw substrings that fully contain @ or /): use match(field, "user_name").
  • To match substrings inside a word (for example, use ana to match banana; tokenized search does not hit fragments inside words): use match(field, "ana") or wildcard(field, "*ana*").
  • To distinguish case or match complex formats: use re(field, "...").
  • For more tokenization details and common examples, see DQL Full-Text Search and Tokenization Rules.

Return value: Boolean value.

Examples:

# Match logs containing the terms "connection" and "timeout"
L::*:(message) {search("connection timeout")} [15m] LIMIT 20

# Chinese matching
L::*:(message) {search("连接超时")} [15m] LIMIT 20

# Mixed Chinese and English
L::*:(message) {search("error 错误")} [15m] LIMIT 20

# Phrase matching with adjacent terms in order; will not match "build succeeded, parse error"
L::*:(message) {search("#\"build error\"")} [15m] LIMIT 20

# Legacy double-quote form; still phrase matching when referer=func
L::*:(message) {search("\"build error\"")} [15m] LIMIT 20

# When only punctuation is included, match directly by consecutive literal substring
L::*:(message) {search("#\"---\"")} [15m] LIMIT 20

Regex Matching

re / regex / regexp

Regular expression matching, case-sensitive.

Syntax:

re(pattern)
re(field, pattern)
regex(pattern)
regex(field, pattern)
regexp(pattern)
regexp(field, pattern)

Parameters:

  • pattern: Regular expression (supports PromRegex syntax)
  • field: Field name (optional)

Return value: re: boolean value; regex: boolean value; regexp: boolean value.

Examples:

# Match logs starting with error; will not match logs starting with ERROR
L::logs:(message) {re("error.*")} [1h]

# Match error codes in a specific format
L::logs:(message) {regexp(message, "ERR-\d{4}")} [1h]

# Use a regular expression in the data source
M::re('cpu.*'):(usage) [1h]

Wildcard Matching

wildcard

Wildcard pattern matching, case-sensitive.

Syntax:

wildcard(pattern)
wildcard(field, pattern)

Parameters:

  • pattern: Wildcard pattern
    • *: Matches any number of characters
    • ?: Matches a single character
  • field: Field name (optional)

Return value: Boolean value.

Examples:

# Match messages starting with error; will not match messages starting with ERROR
L::logs:(message) {wildcard("error*")} [1h]

# Match a specific format
L::logs:(message) {wildcard(message, "ERR-????")} [1h]

CIDR Matching

cidr

IP address subnet matching.

Syntax:

cidr(cidr)
cidr(field, cidr)

Parameters:

  • cidr: Subnet in CIDR notation, such as 192.168.1.0/24
  • field: IP address field (optional)

Return value: Boolean value.

Examples:

# Match private IPs
L::nginx:(*) {cidr(client_ip, "10.0.0.0/8")} [1h]

# Match a specific subnet
L::nginx:(*) {cidr(client_ip, "192.168.1.0/24")} [1h]

Field Existence Check

exists

Checks whether a field exists. exists() is a special placeholder, usually placed on the right side of a comparison expression.

Syntax:

exists()

Recommended usage:

field = exists()   // Field exists (non-null)
field != exists()  // Field does not exist or is null

Parameters:

Parameter Type, requirements, and meaning
field Field on the left side of the comparison operation; exists() itself does not accept parameters

Return value: The comparison expression returns a boolean value: the equality form checks that the field is non-null, and the inequality form checks that it is missing or null.

Examples:

# Find logs that have the error_type field
L::logs:(message) {error_type = exists()} [1h]

# Find logs that do not have the error_type field
L::logs:(message) {error_type != exists()} [1h]

Query String Syntax

query_string

Uses query string syntax for complex matching.

Usage notes:

  • The ScopeDB environment uses case-insensitive containment search and does not use the same full-text tokenization process described below.
  • The Doris environment is based on full-text indexes and tokenized matching; the term, boolean combination, phrase, and pattern syntax below should be understood in combination with the support scope of the current storage engine.

When you need to limit the search field, explicitly use query_string(field, query) to avoid interpreting the default full-text search scope as a fixed field.

Syntax:

query_string(query)
query_string(field, query)

Parameters:

  • query: Query string
  • field: Field name (optional; defaults to full-text matching)

Return value: Boolean condition used in WHERE.

Query string syntax:

1. Term Matching
foo              # Match content containing foo
"foo bar"        # Exact phrase match; must appear consecutively
foo\ bar         # Escape space and match the whole "foo bar"
2. Wildcards
foo*             # Match content starting with foo
foo?bar          # ? matches a single character
"foo*bar"        # Wildcards inside quotes are not parsed and are matched as literals
3. Regular Expressions
/foo.*bar/       # Regular expression wrapped in slashes
/joh?n(ath[oa]n)/  # Complex regular expression
4. Boolean Operators
foo AND bar      # Logical AND; both must be included
foo OR bar       # Logical OR; at least one must be included
NOT foo          # Logical NOT; does not include foo

# Shorthand forms
foo && bar       # Equivalent to foo AND bar
foo || bar       # Equivalent to foo OR bar
!foo             # Equivalent to NOT foo
5. Grouping
(foo OR bar) AND baz       # Use parentheses to change precedence
!(status 429 reading)      # Negate the entire expression
6. Default Operator

In full-text search, multiple terms separated by spaces are joined by AND by default. You can also explicitly specify AND or OR in the query.

foo bar          # Equivalent to foo AND bar
7. Tokenization and Matching Rules

Each ordinary term and phrase in query_string follows the same tokenization rules as search:

  • Term splitting: Consecutive letters and numbers form one term (case is ignored), and Chinese is split by words or characters; spaces and various punctuation marks (such as ., _, :, /, -, @, =, etc.) are all treated as separators. For example, query_string("user_name") searches for data containing both the user and name terms.
  • Phrase matching: When wrapped in double quotes (such as query_string("\"connection reset\"")) or when spaces are escaped (such as query_string("connection\\ reset")), the tokenized terms must appear adjacent in order.
  • To match punctuation or substrings inside words: Because punctuation is treated as a separator during tokenization, if you need to strictly distinguish punctuation (such as distinguish user_name from user.name) or match substrings inside words, use the match function or use a /.../ regular expression in query_string.
  • For detailed splitting rules and common examples, see DQL Full-Text Search and Tokenization Rules.

Examples:

# Simple term matching
L::*:(message) {query_string("error timeout")} [15m] LIMIT 20

# Boolean combination
L::*:(message) {query_string("error AND NOT timeout")} [15m] LIMIT 20

# Regular expression
L::*:(message) {query_string("/ERR-\\d{4}/")} [15m] LIMIT 20

# Complex query
L::*:(message) {query_string("(error OR warn) AND timeout")} [15m] LIMIT 20

# Specify a field
L::*:(*) {query_string(message, "error AND timeout")} [15m] LIMIT 20

# Chinese query
L::*:(message) {query_string("错误 AND 超时")} [15m] LIMIT 20

Outer Functions

Usage recommendation: Outer functions are a legacy design. For scenarios that can be solved with Rollup + aggregation functions (such as [rate], [last], [increase], etc.), prefer the Rollup approach. Use outer functions only in scenarios where Rollup is not applicable (such as when secondary calculation on aggregate results is required). Detection or forecasting functions that require complete query results, such as dbscan, anomalies, outliers, and forecast, do not have equivalent Rollup syntax and are used as outer functions.

Outer functions operate on the entire DQL query result and are used for secondary calculation on the time series data output by the query. Outer functions wrap the entire DQL expression rather than being written inside the Select clause.

In-Query Functions and Outer Functions

  • In-query functions: Used inside DQL expressions, such as sum, avg, max, etc.
  • Outer functions: Wrap the entire DQL query result and post-process the output time series

Syntax comparison:

# Rollup (time clause): first calculate the growth rate for each time series, then aggregate
M::http_requests:(sum(request_count)) [rate] BY service

# Outer function: first obtain the query result, then perform secondary calculation
rate(M::http_requests:(sum(request_count)) [1h::1m] BY service)

Syntax:

outer_function(DQL_expression)

Examples:

# In-query function: calculate the average of raw data
M::cpu:(avg(usage)) [1h::5m] BY host

# Outer function: calculate a moving average on the query result
moving_average(M::cpu:(avg(usage)) [1h::5m] BY host, 5)

Cumulative Calculation

cumsum

Calculates the cumulative sum, computing for each point in the time series the accumulated value of all preceding points.

Syntax:

cumsum(DQL_expression)

Parameters:

Parameter Type, requirements, and meaning
query Required; complete DQL query whose output is processed by the outer function

Return value: A cumulative value sequence corresponding to each time point.

Examples:

# First count logs in each window, then accumulate the result point by point
cumsum(L::logs:(count(*)) [1h::5m] BY service)

Differences and Derivatives

Recommended usage: These functions should preferably be used as Rollup functions (such as [rate], [deriv]). The outer function form is only used for secondary calculation on aggregate results.

The following functions can be used as outer functions:

Function Description
derivative(DQL) Calculate derivative (rate of change)
difference(DQL) Calculate the difference from the previous value
non_negative_derivative(DQL) Calculate non-negative derivative
non_negative_difference(DQL) Calculate non-negative difference
rate(DQL) Calculate growth rate (per second)
irate(DQL) Calculate instantaneous growth rate

Examples:

# Outer function: calculate the derivative of the query result
derivative(M::cpu:(avg(usage)) [1h::5m] BY host)

# Recommended: use the Rollup approach
M::cpu:(deriv(usage)) [1h::5m:last] BY host

Moving Calculations

moving_average

Calculates the moving average on the query result.

Call location: moving_average(field, n) is an explicit in-query call; time clause Rollup is written as [...:moving_average(n)]. The outer moving_average(DQL_expression, n) is used for secondary smoothing of an already aggregated result sequence.

Syntax:

moving_average(DQL_expression, n)

Parameters:

  • DQL_expression: DQL query expression
  • n: Window size (number of data points)

Return value: Processed moving average sequence.

Examples:

# Outer function: calculate a moving average on the query result
moving_average(M::cpu:(avg(usage)) [1h::1m] BY host, 5)

# Explicit in-query call: input differs from the outer form
M::cpu:(moving_average(usage, 5)) [1h::1m] BY host

Time Series Analysis and Anomaly Detection

anomalies

Compares a time series with its own historical baseline to identify time series anomaly points that deviate from historical patterns. Supports non-seasonal rolling baselines, daily/weekly/hourly seasonal baselines, level adaptation, and automatic selection.

Syntax:

anomalies((<metrics-dql>), algorithm='basic|robust|agile|auto', seasonality='hourly|daily|weekly|auto', history='auto'|<duration>, band='mad|quantile', deviation=3, lower_q=0.01, upper_q=0.99, recent_window=30m)

Parameters:

  • (<metrics-dql>): Inner native Metrics DQL query (must have a time window and fixed step, with a single numeric measure).
  • algorithm: Algorithm type, optional, default basic:
  • basic: Non-seasonal rolling baseline, suitable for stable metrics or metrics without a fixed period.
  • robust: Seasonal robust baseline (calculated by slot median + MAD), suitable for strongly seasonal metrics.
  • agile: Seasonal adaptive baseline, able to quickly adapt to recent step-like level drift.
  • auto: Automatic selection; automatically selects the optimal seasonality based on historical autocorrelation coefficients or degrades to basic.
  • seasonality: Seasonal slot type: hourly, daily, weekly, auto. robust and agile must explicitly specify it.
  • history: Length of the historical warm-up window, default auto (basic is max(12*step, 1h); robust/agile is 6 full periods).
  • band: Normal interval algorithm: mad (default) or quantile (only basic).
  • deviation: Multiplier for the normal interval width (default 3 for the MAD branch).
  • lower_q / upper_q: Lower/upper quantiles (default 0.01 / 0.99 for the quantile branch).
  • recent_window: Level adjustment window (30m by default for agile).

Return value (standardized wide table):

Column name Type Description
time int64 Timestamp
value float64/null Actual observed value
expected float64/null Model expected baseline value
lower / upper float64/null Lower and upper bounds of the normal interval
residual float64/null Residual between the actual value and expected value
score float64/null Deviation score
is_anomaly int64/null Anomaly flag: 1 (anomaly) or 0 (normal)
status string Status: ok, missing, insufficient_history, undefined_model, etc.
algorithm string Algorithm actually in effect

Examples:

# Daily seasonal historical anomaly detection
anomalies((M::cpu:(avg(usage_total) AS value) [2h::5m] BY host), algorithm='robust', seasonality='daily')

# Composite condition alert in eval (value exceeds upper limit and deviation score > 1)
eval(
  A.value > A.upper AND A.score > 1,
  A=anomalies((M::cpu:(avg(usage_total) AS value) [2h::5m] BY host), algorithm='robust', seasonality='daily')
)

outliers

At the same time point, horizontally compares different series within the same peer set (such as different pods or hosts in a cluster) to identify outliers that deviate from peers.

Syntax:

outliers((<metrics-dql>), algorithm='mad|dbscan', peer_by=['tag1', ...], tolerance=3, eps=0.5, min_peers=3, scaled=false)

Parameters:

  • (<metrics-dql>): Inner native Metrics DQL query.
  • peer_by: Required, string array. Specifies the subset of BY labels used to divide peer sets (for example, ['cluster'] means comparing machines within the same cluster).
  • algorithm: Outlier algorithm, mad (cross-sectional median absolute deviation, default) or dbscan (one-dimensional density clustering).
  • tolerance: MAD deviation tolerance multiplier, default 3.
  • eps: DBSCAN neighborhood distance, default 0.5.
  • min_peers: Minimum number of peers required for determination, default 3 (marked as insufficient_peers when insufficient).
  • scaled: Whether to use scale normalization, default false.

Return value (standardized wide table):

Column name Type Description
time int64 Timestamp
value float64/null Actual value of the current peer
expected float64/null Median of peers in the same group (null for DBSCAN)
lower / upper float64/null Lower/upper bounds of the normal range for the same group
score float64/null Outlier score
is_outlier int64/null Outlier flag: 1 (outlier) or 0 (non-outlier)
peer_count int64/null Number of valid peers participating in the comparison
status string Status: ok, insufficient_peers, etc.

Examples:

# Detect hosts whose CPU deviates from peers within the same cluster
outliers((M::cpu:(avg(usage_total) AS value) [1h::5m] BY cluster, host), peer_by=['cluster'], algorithm='mad')

forecast

Forecasts future trends and seasonality of a time series, outputting predicted values and dynamic confidence intervals for future time points.

Syntax:

// Enhanced canonical form
forecast((<metrics-dql>), algorithm='linear|seasonal|auto', seasonality='hourly|daily|weekly|auto', history='auto'|<duration>, steps=5, deviations=3)

// Compatible shorthand form
forecast(DQL_expression, steps)

Parameters:

  • (<metrics-dql>): Inner native Metrics DQL query.
  • algorithm: Forecasting algorithm, default linear:
  • linear: Linear trend extrapolation with diverging confidence bands.
  • seasonal: Seasonal slot baseline + level drift correction + linear trend extrapolation.
  • auto: Automatic selection; uses seasonal when autocorrelation is significant, otherwise degrades to linear.
  • seasonality: Seasonality type (hourly, daily, weekly, auto).
  • history: Historical warm-up window, default auto (linear is max(12*step, 1h); seasonal is 6 periods).
  • steps: Number of future points to forecast, optional, default 5, must be a positive integer.
  • deviations: Confidence band width multiplier, default 3.

Return value (standardized wide table):

Column name Type Description
time int64 Future forecast timestamp sequence ($To + k \cdot step$)
forecast float64/null Forecast value for future points
lower / upper float64/null Lower and upper bounds of the dynamic confidence interval (naturally diverging with steps)
status string Status: ok, insufficient_history, zero_variance
algorithm string Algorithm actually in effect

Examples:

# Forecast CPU trends for the next 12 points (1 hour), considering daily seasonality
forecast((M::cpu:(avg(usage_total) AS value) [2h::5m] BY host), algorithm='seasonal', seasonality='daily', steps=12)

# Capacity limit forecast alert in eval (future mean exceeds 90% or upper bound exceeds 95%)
eval(
  F.forecast > 90 OR F.upper > 95,
  F=forecast((M::cpu:(avg(usage_total) AS value) [2h::5m] BY host), algorithm='seasonal', seasonality='daily', steps=12)
)

dbscan

Performs DBSCAN outlier detection on numeric time series in the query result and outputs numeric anomaly flags.

Syntax:

dbscan(DQL_expression)
dbscan(DQL_expression, eps)

Parameters:

  • DQL_expression: DQL query expression. Usually used for multi-series query results with a time window and BY grouping.
  • eps: Neighborhood distance threshold, optional, default 0.5, range (0, 3.0].

Return value:

  • Outputs one corresponding dbscan(column) numeric column for each numeric column.
  • 1 indicates an outlier, and 0 indicates a non-outlier.
  • Returns a null value when there are fewer than 5 valid numeric points, indicating insufficient samples and no detection performed.

Description:

  • At least 5 valid numeric points are required; returns a null value when there are insufficient valid points.
  • The current implementation performs one-dimensional DBSCAN separately for each numeric column in the input table and retains the time column.

Examples:

# Detect CPU usage outliers with default eps=0.5
dbscan(M::cpu:(avg(usage)) [1h::5m] BY host)

# Explicitly specify eps
dbscan(M::cpu:(avg(usage)) [1h::5m] BY host, 0.8)

TopN

top / bottom

Call location: top(field, n) and bottom(field, n) are in-query aggregation calls; top(DQL_expression, n) and bottom(DQL_expression, n) receive a complete query and filter the aggregate results again. Do not call in-query calls time clause Rollup.

Gets TopN or BottomN on the query result.

Syntax:

top(DQL_expression, n)
bottom(DQL_expression, n)

Parameters:

Parameter Type, requirements, and meaning
query Required; complete DQL query whose output is processed by the outer function
n Required; positive integer, number to select

Return value: top(query, n): TopN or BottomN values selected from the inner result; bottom(query, n): TopN or BottomN values selected from the inner result.

Examples:

# Outer function: get TopN from the query result
top(M::response_time:(max(duration)) [1h::5m] BY service, 5)

# In-query aggregation call: get TopN from raw input
M::response_time:(top(duration, 5)) [1h::5m] BY service

Null Value Filling

fill

Fills null values in the query result.

For details, see fill function.

Examples:

# Fill null values with 0
fill(M::cpu:(avg(usage)) [1h::5m] BY host, 0)

# Fill with linear interpolation
fill(M::cpu:(avg(usage)) [1h::5m] BY host, LINEAR)

Other Outer Functions

The following functions can also be used as outer functions:

Function Description
abs(DQL) Absolute value
round(DQL[, digits]) Round
ceil(DQL) Round up
floor(DQL) Round down
log(DQL) / log2(DQL) / log10(DQL) Logarithmic transformation
set(DQL) Deduplicate and sort
concat(DQL, ...) String concatenation

Combined Usage

Outer functions can be combined:

# Calculate moving average and then round
round(moving_average(M::cpu:(avg(usage)) [1h::1m] BY host, 5))

# Calculate the moving average of the growth rate
moving_average(rate(M::requests:(sum(count)) [1h::5m] BY service), 3)

eval Expression Evaluation

eval is a special function that allows expression evaluation outside the query, and can reference results from multiple subqueries for combined operations.

Syntax

eval(expression, name1=(query1), name2=(query2), ..., alias="result_name")

Parameters:

  • expression: Mathematical expression that references subquery results using name.field
  • name=(query): Named subquery
  • alias: Result alias (optional)

Note: eval also supports the historical syntax name="query", but name=(query) is recommended for type expression and readability.

How It Works

  1. Execute all named subqueries
  2. Align the results of each subquery by time
  3. Calculate the expression for each time point
  4. Return the calculation result

Use Cases

  • Calculate ratios of multiple metrics (such as error rate or utilization)
  • Compare metrics from different time periods
  • Combine calculation results from multiple data sources

Examples

Calculate Error Rate

# In this example, error_count and request_count represent the number of new records
# Error rate = errors / total requests * 100
eval(a.errors / b.requests * 100,
     a=(M::http:(sum(error_count) AS errors) [1h] BY service),
     b=(M::http:(sum(request_count) AS requests) [1h] BY service),
     alias="error_rate")

Calculate Memory Usage

# Usage = used / total * 100
eval(used.value / total.value * 100,
     used=(M::memory:(sum(used_bytes) AS value) [1h] BY host),
     total=(M::memory:(sum(total_bytes) AS value) [1h] BY host),
     alias="memory_usage_percent")

Calculate Growth Rate Compared with Baseline

# Calculate the growth rate of the current value relative to the baseline value
eval(current.value / baseline.value - 1,
     current=(M::sales_current:(sum(amount) AS value) [7d]),
     baseline=(M::sales_baseline:(sum(amount) AS value) [7d]),
     alias="growth_rate")

Calculate Network Packet Error Rate

# Receive packet error rate = err_in / packets_recv * 100
eval(err / pkt * 100,
     err=(M::net:(sum(err_in)) [1h::5m:increase] BY host),
     pkt=(M::net:(sum(packets_recv)) [1h::5m:increase] BY host),
     alias="packet_error_rate")

Reference Fields from Subqueries

# Reference a specific field from a subquery
eval(a.usage / b.total * 100,
     a=(M::cpu:(avg(usage) as usage) [1h] BY host),
     b=(M::cpu:(avg(total) as total) [1h] BY host),
     alias="cpu_percent")

Notes

  • Subqueries used in the same expression should keep consistent time ranges, aggregation steps, and grouping keys to facilitate result alignment.
  • The examples in this document explicitly set output column aliases for subqueries and then reference them using name.field, avoiding confusion among subquery names, raw fields, and aggregate columns.
  • Historical queries may directly reference fields or single-column subquery names; new queries should specify column names explicitly where possible.
  • When calculating ratios, handle cases where the denominator is zero or missing; do not assume that missing values are automatically filled with zero.

Other Functions

fill

Fills null values in the query result with a specified value.

Recommended usage: fill is recommended as an outer function, operating on the entire query result:

fill(M::cpu:(avg(usage)) [1h::5m] BY host, 0)

Although fill(avg(usage), 0) is also supported in the Select clause, fill actually fills the result after aggregation is complete, so the outer function form better matches its working mechanism.

Syntax (outer function):

fill(DQL_expression, value)
fill(DQL_expression, LINEAR)
fill(DQL_expression, PREVIOUS)

Parameters:

  • DQL_expression: DQL query expression
  • value: Fill value, supporting multiple modes:
    • Specific value: number, string, null
    • LINEAR: Linear interpolation
    • PREVIOUS: Fill with the previous non-null value

Filling applies to the result sequence already produced by the query; when a field in the raw record is empty, use default. For example, if the middle of three equally spaced result points is empty, the meanings of the three modes are as follows:

Original result Fill method Filled result
[10, nil, 30] 0 [10, 0, 30]
[10, nil, 30] PREVIOUS [10, 10, 30]
[10, nil, 30] LINEAR [10, 20, 30]

This example has an available previous value and interpolation endpoints; do not directly apply the result for a missing middle point to series boundaries that lack reference points.

Examples:

# Recommended: use as an outer function
fill(M::cpu:(avg(usage)) [1h::5m] BY host, 0)

# Fill with linear interpolation
fill(M::cpu:(avg(usage)) [1h::5m] BY host, LINEAR)

# Fill with the previous value
fill(M::cpu:(avg(usage)) [1h::5m] BY host, PREVIOUS)

now

Returns the current timestamp (milliseconds).

Syntax:

now()

Parameters:

Parameter Type, requirements, and meaning
None Does not accept parameters

Return value: Millisecond Unix timestamp.

Examples:

# Query recently updated data
O::HOST:(*) {last_update_time > now() - 600000}  # Updated within 10 minutes

unwrap

Unwraps the wrapper of an aggregate result.

Syntax:

unwrap(field)

Parameters:

Parameter Type, requirements, and meaning
field Required; field or expression to process

Return value: The value inside the wrapper; the type depends on the actual expression.

Examples:

# Unwrap an aggregated field
M::cpu:(unwrap(usage)) [1h] BY host

Show Functions

Show functions are used to view metadata (such as measurements, tags, fields, cardinality, and series counts). They are often used for modeling troubleshooting and pre-query exploration.

General Syntax

show_xxx(arg1=..., arg2=...){ where_conditions } [time_window] LIMIT n OFFSET m
  • where, time_window, LIMIT, and OFFSET are all optional.
  • LIMIT/OFFSET cannot be negative.

Built-in Show Functions in the M Namespace

Function Parameters Returned columns Description
show_measurement Optional re('pattern') name List measurements
show_tag_key Optional from=['measurement'] tagKey List tag keys
show_field_key Optional from=['measurement'] fieldKey, fieldType List field keys (currently fieldType is float)
show_tag_value keyin=['tagKey'] (required), optional from key, value List tag values
show_measurement_cardinality No mandatory parameters count Number of measurements
show_series_cardinality No mandatory parameters count Series cardinality (estimated)
show_tag_key_cardinality No mandatory parameters count Tag key cardinality (estimated)
show_tag_value_cardinality keyin=['tagKey'] (required) count Value cardinality for the specified tag key (estimated)
show_field_key_cardinality No mandatory parameters count Field key cardinality (estimated)
show_series_count_by_field_key from=['measurement'] or equivalent source condition (one of the two is required) name, count Count series by field key
show_series_count_by_tag_key from=['measurement'] or equivalent source condition (one of the two is required) name, count, value_count Count series and values by tag key
show_series_count_by_tag_value keyin=['tagKey'] (required); from=['measurement'] or equivalent source condition (one of the two is required) name, count Count series by values of the specified tag key

Cardinality-related functions use HyperLogLog merging internally and return estimated values.

Below are the minimal complete calls for each metric Show function. cpu and host must be replaced with the actual measurement and tag key:

Function Complete query example
show_measurement show_measurement()
show_tag_key show_tag_key(from=['cpu'])
show_field_key show_field_key(from=['cpu'])
show_tag_value show_tag_value(from=['cpu'], keyin=['host'])
show_measurement_cardinality show_measurement_cardinality()
show_series_cardinality show_series_cardinality()
show_tag_key_cardinality show_tag_key_cardinality()
show_tag_value_cardinality show_tag_value_cardinality(keyin=['host'])
show_field_key_cardinality show_field_key_cardinality()
show_series_count_by_field_key show_series_count_by_field_key(from=['cpu'])
show_series_count_by_tag_key show_series_count_by_tag_key(from=['cpu'])
show_series_count_by_tag_value show_series_count_by_tag_value(from=['cpu'], keyin=['host'])

Show Functions in Non-M Namespaces (Suffix Mode)

You can query sources, fields, indexes, or labels through an explicit namespace parameter, for example show_source(namespace='L'), show_field(namespace='L', source='mysql'), show_index(namespace='L'), and show_label(namespace='L', name='env').

For non-M namespaces, the following suffix modes are supported:

  • show_<namespace>_source
  • show_<namespace>_class
  • show_<namespace>_type
  • show_<namespace>_field
  • show_<namespace>_label

Here, <namespace> is automatically mapped from the middle segment of the function name, for example:

  • show_logging_source -> L
  • show_tracing_field -> T
  • show_object_source -> O

For source and field discovery in Data Observability, Agent, and LLM, use the following syntax. Do not directly concatenate abbreviations into dedicated function names:

Namespace List sources List fields
LN, Data Observability show_source(namespace='LN') show_field(namespace='LN')
AM, Agent Monitoring show_agent_monitor_source() show_agent_monitor_field('agent_trace')
LLM, LLM Monitoring show_large_lang_model_source() show_large_lang_model_field('llm_trace')

LN uses the general Show functions with an explicitly specified namespace; when source is omitted from a field query, the source is not limited, and source can also be passed to limit to a specific source. The functions for AM use agent_monitor, and those for LLM use large_lang_model; agent_trace and llm_trace should be filled in according to the actual results of the source query.

Common examples:

show_logging_source()

show_tracing_field('mysql')

show_logging_field('*')

show_logging_label(name='env')

show_logging_label(names=['env', 'team'])

Parameters and Behavior

  • from: List of measurements, supporting a string or string array.
  • keyin: List of tag keys, supporting a string or string array.
  • field: List of fields, supporting a string or string array (used for field filtering in metric show).
  • For show_*_field:
    • Unnamed parameters (such as 'mysql') are usually used as source filters.
    • '*' is equivalent to not specifying a source.
    • Named parameters are converted into where filter conditions.
  • For show_*_label:
    • Named parameters are required; names is treated as an alias for name.

Constraints and Notes

  • show_tag_value and show_tag_value_cardinality must provide keyin.
  • show_series_count_by_tag_value must provide keyin.
  • show_series_count_by_* must provide from, or provide an equivalent source constraint in where (for example, an @__source__ condition).
  • show_<namespace>_source, show_<namespace>_class, and show_<namespace>_type currently share the same execution path and return a deduplicated source list.
  • Currently, the parser does not support the show_<namespace>_index syntax (even if a corresponding branch exists in the execution layer).
  • When the Query API does not provide a show time range, some log show queries fall back to executing over the most recent 30-minute window.

Return Examples

The following examples show only typical column structures and sample rows; actual results are affected by tenant data, filter conditions, time range, and LIMIT/OFFSET.

Query Typical columns Example rows (illustrative)
show_measurement() name cpu, disk, memory
show_tag_value(from=['cpu'], keyin=['host']) key, value host, web-01; host, web-02
show_series_count_by_tag_key(from=['cpu']) name, count, value_count host, 3200, 120; service, 2800, 35
show_tag_value_cardinality(keyin=['host']) count 120
show_logging_field('*') fieldKey, fieldType, fieldIndices service, keyword, ["idx_service"]
show_logging_source() source nginx, mysql, redis

Function Quick Reference

Basic Aggregations

Function Description Exact/Estimated
sum Sum Exact
avg Average Exact
count Count Exact
count_distinct Distinct count Estimated (HyperLogLog, error ≈ 0.4%)
min / max Minimum/maximum Exact
first / last First/last value Exact
any Any value Exact

Statistical Aggregations

Function Description Exact/Estimated
percentile / pXX Percentile Estimated (log histogram)
median Median Estimated
stddev Standard deviation Exact
mode Mode Exact
spread Range Exact
count_series Number of time series Exact

Time Series Analysis Aggregations

Function Description Notes
ewma Exponentially weighted moving average Supports [...:ewma(alpha)]
slope Linear trend slope Can be used as Rollup shorthand
zscore Z-Score of the latest point Can be used as Rollup shorthand
mad_score MAD anomaly score of the latest point Can be used as Rollup shorthand
change_score Series change score Can be used as Rollup shorthand
corr Pearson correlation coefficient of two fields Requires two input fields

Filtered Aggregations

Function Description Exact/Estimated
top / bottom TopN / BottomN Exact
count_filter Conditional count Exact

Histogram Functions

Function Description Applicable data source Exact/Estimated
histogram_auto Automatic histogram (Recommended) Log and trace detail data Estimated
histogram Fixed bucket boundary histogram (deprecated) Log and trace detail data Exact
histogram_quantile Calculate quantiles from Prometheus histograms Prometheus metrics Estimated

Collection Functions

Function Description Exact/Estimated
distinct List of distinct values Exact
distinct_by_collapse Collapsed deduplication (retains other fields) Exact
collect Collect all values Exact
collect_distinct Collect distinct values Exact

Helper Functions

Function Description Exact/Estimated
default Set default value Exact

Time Series Functions

Function Description
rate Growth rate (per second)
irate Instantaneous growth rate
increase Increase
derivative Derivative
difference Difference
non_negative_derivative Non-negative derivative
non_negative_difference Non-negative difference
moving_average Moving average
cumsum Cumulative sum
ewma Exponentially weighted moving average
slope Trend slope
zscore Z-Score of the latest point
mad_score MAD anomaly score
change_score Change score
corr Correlation coefficient

Rollup Functions

Function Description
rate Calculate growth rate (per second)
irate Calculate instantaneous growth rate
increase Calculate increase
rate_over_sum Calculate average per second
rate_over_count Calculate count per second
deriv Calculate derivative
difference Calculate difference
sum Sum
avg Average
min Minimum
max Maximum
count Count
first First value
last Last value
stddev Standard deviation
mode Mode
spread Range
any Any value
ewma(alpha) Exponentially weighted moving average
moving_average(n) Moving average
percentile(p) Percentile
slope Linear trend slope
zscore Z-Score of the latest point
mad_score MAD anomaly score of the latest point
change_score Series change score

Transformation Functions

Function Description
abs Absolute value
round / ceil / floor Rounding
log / log2 / log10 Logarithm
int / uint / float / string / bool Type conversion
substr Substring
regexp_extract Regex extraction
regexp_extract_all Regex extract all
regexp_replace Regex replacement
md5 MD5 hash
concat String concatenation
set Array deduplication and sorting
drain Log clustering

Matching Functions

Function Description
match Substring matching
phrase / search Tokenized phrase matching
re / regex / regexp Regex matching
wildcard Wildcard matching
cidr CIDR subnet matching
query_string Query string syntax
exists Field existence check

Outer Functions

Function Description
cumsum Cumulative sum
rate / irate Growth rate (non-negative)
deriv Derivative (negative values allowed)
increase Increase (non-negative)
difference Difference (negative values allowed)
moving_average Moving average
top / bottom TopN
dbscan DBSCAN outlier detection
anomalies Compare with historical baseline and identify time series anomalies
outliers Identify outlier series at the same time point
forecast Forecast future trends and seasonality
fill Null filling (recommended as an outer function)
abs / round / ceil / floor Mathematical operations
set Deduplication and sorting
concat String concatenation

Expression Evaluation

Function Description
eval Multi-query expression evaluation