Skip to content

DQL


DQL (Debug Query Language) is the core query language of the Guance platform, designed for efficient querying and analysis of time series data, log data, event data, and more. DQL combines SQL's semantic expressiveness with PromQL's syntax structure, aiming to provide users with a flexible and powerful query tool.

This document will help you quickly understand DQL's basic syntax and design concepts, and show how to write DQL queries through examples.

The Measurements, sources, and field names in this document are used to illustrate syntax; replace them with names that actually exist when using them. The default log index name is default; nginx, logs, etc. are example log sources and do not indicate the default index. For function parameters, return values, and differences between similar functions, see DQL Functions Reference.

Basic Query Structure

The basic query structure of DQL is as follows:

namespace(index)::datasource[:select-clause] [{where-clause}] [time-expr] [SHIFT duration] [group-by-clause] [having-clause] [order-by-clause] [limit-clause] [offset-clause] [sorder-by-clause] [slimit-clause] [soffset-clause]

Here index can be omitted; when omitted, the default index is used by default.

The namespace(index) above uses actual parentheses to declare the index; when the index is omitted, the parentheses are also omitted. The remaining square brackets indicate optional parts of the structure. In actual queries, the select expression is written as :(...), raw data filtering is written in {...}, and the time clause is written in [...]. Query-level SHIFT is written after the time clause and before BY.

When the data source is omitted, you can directly use parentheses to specify projections:

namespace(index)::(select-clause) [{where-clause}] [time-expr] [group-by-clause] ...

For example:

M::(usage_total)

M::(sum(bytes_recv) AS total) BY host

When there are no parentheses, the expression after :: still represents the data source (Note: metric query M does not support the default all-fields *; fields must be specified explicitly. For non-metric namespaces such as logs L, omitting fields returns all fields * by default):

L::nginx

M::cpu:(usage_total)

Therefore, M::(cpu) means selecting the field cpu, and no longer means the data source cpu; if you need to explicitly specify fields for a parenthesized data source, write L::(nginx):(*) or M::(cpu):(usage_total).

When a derived table is used as a data source, the explicit projection separator is still used:

M::(M::cpu:(avg(usage_total) AS avg_usage) [1h] BY host):(max(avg_usage))

Here the outer (...) is the subquery data source, and the immediately following :(...) is the outer projections.

Execution Order

The execution order of a DQL query is very important because it determines the query's semantics and performance.

  1. Data filtering: Filter data based on namespace::datasource, where-clause, and time-expr

    • Determine the data source
    • Apply WHERE conditions to filter raw data rows
    • Apply time range filtering
    • Filter data as early as possible at this stage to improve the efficiency of subsequent processing
  2. Time aggregation: If time-expr contains rollup, execute the rollup logic first

    • Rollup functions preprocess data along the time dimension
    • For Counter metrics, rate or increase is usually calculated instead of directly using raw values
    • For Gauge metrics, aggregation functions such as last and avg may be used
  3. Group aggregation: Execute group-by-clause grouping and execute aggregation functions in select-clause within each group

    • Group data according to the expressions in the BY clause
    • Calculate aggregation functions (sum, count, avg, max, min, etc.) within each group
    • If there is also a time window, a two-dimensional data structure is formed
  4. Group filtering: Execute having-clause to filter aggregated groups

    • The HAVING clause acts on aggregated results
    • Aggregation function results can be used for filtering
    • This is the key difference from the WHERE clause
  5. Non-aggregation functions: Execute non-aggregation functions in select-clause

    • Process expressions and functions that do not require aggregation
    • Perform further calculations on aggregation results
  6. Intra-group sorting: Execute order-by-clause and limit-clause to sort and paginate data within groups

    • ORDER BY is executed independently within each group
    • LIMIT limits the number of data rows returned per group
  7. Inter-group sorting: Execute sorder-by-clause, slimit-clause, and soffset-clause to sort and paginate groups

    • SORDER BY sorts the groups themselves
    • Group results need to be reduced in dimension (for example, using functions such as max, avg, and last)
    • SLIMIT limits the number of groups returned

Complete Example

Let's use a complete example to understand the structure of DQL:

M::cpu:(avg(usage) as avg_usage, max(usage) as max_usage) {host =~ 'web-.*', usage > 50} [1h::5m] BY host, env HAVING avg_usage > 60 ORDER BY time DESC LIMIT 100 SORDER BY avg_usage DESC SLIMIT 10

The meaning of this query is:

  • Namespace: M (metric data)
  • Index: Not explicitly declared
  • Data source: cpu
  • Select fields: Average and maximum values of the usage field
  • Time range: The past 1 hour, aggregated by 5 minutes
  • Filter conditions: Hostname starts with web and CPU usage is greater than 50%
  • Grouping: Group by hostname and environment
  • Group filtering: Average CPU usage is greater than 60%
  • Sorting: Sort by time in descending order, with at most 100 records per group
  • Inter-group sorting: Sort by average usage in descending order, with at most 10 groups

Namespace (namespace)

Namespaces distinguish different types of data; each data type has its specific query method and storage policy. DQL supports querying a variety of business data types:

Namespace Description Typical Use Cases
M Metric, time series metric data CPU usage, memory usage, request count, etc.
L Logging, log data Application logs, system logs, error logs, etc.
O Object, infrastructure object data Server information, container information, network devices, etc.
OH History object, object history data Server configuration change history, performance metric history, etc.
CO Custom object, custom object data Business-defined object information
COH History custom object, custom object history data Historical change records of custom objects
N Network, network data Network traffic, DNS queries, HTTP requests, etc.
T Trace, trace call data Distributed tracing, call chain analysis, etc.
P Profile, profiling data Performance profiling, CPU Flame Graph, etc.
R RUM, RUM data Frontend performance, user behavior analysis, etc.
E Event, event data Alert events, deployment events, system events, etc.
UE Unrecovered Event, unrecovered event data Unresolved alerts and events
B Cloud billing, cloud bills
D Dialtest, synthetic testing data Synthetic test results, response time, and availability
S Security, security data Security detection and analysis
EH ErrorHub, error tracking data Error aggregation and tracking
BL Backup log, backup logs Backed-up log data
TAE Audit events Operation audit records of the Workspace
EL Execution log, execution logs Records of the execution process of rules, tasks, etc.
LN Data Observability Jobs, runs, data assets, and lineage records
AM Agent Monitoring AI Agent session and call data
LLM LLM Monitoring LLM calls, latency, and Token usage
RM RUM Metrics Metrics generated from RUM data
NM Network Metrics Metrics generated from network data
TM Trace Metrics Metrics generated from trace data

AM and LLM query Agent and LLM monitoring data respectively; LN queries Data Observability records. R, N, and T query raw monitoring records, while RM, NM, and TM query the corresponding metric data; they cannot be directly interchanged. Whether a namespace is available depends on feature activation, data ingestion, and query permissions; some types do not appear in the drop-down lists of all query entry points. For how to discover sources and fields, see Show Functions.

The following basic queries read Data Observability, Agent, and LLM records respectively:

LN::*:(*) [1h] LIMIT 10

AM::agent_trace:(*) [1h] LIMIT 10

LLM::llm_trace:(*) [1h] LIMIT 10

LN::* does not limit the source; agent_trace and llm_trace are examples of specific sources. Before querying, confirm the actual sources and fields in the Workspace.

Platform Default Data Sources and Common Fields Quick Reference

The following table lists common data sources and fields. Available data sources and fields depend on the Workspace's collection and ingestion configuration.

Namespace Common Default Data Sources (source / measurement) Common Standard Fields / Tags
M (Metrics) cpu, mem, disk, diskio, net, system cpu: usage_total, usage_user, usage_system, usage_idle, usage_iowait
mem: used_percent, available_percent, used, total, available
disk: used_percent, free, used, total, inodes_used_percent (tags: device, fstype)
net: bytes_recv, bytes_sent, packets_recv, packets_sent, err_in, err_out (tag: interface)
system: load1, load5, load15, load1_per_core, n_cpus, uptime
Common tag: host
L (Logs) * (all logs), nginx, system, etc. message (log body), status (log level: error/warn/info, etc.), service, source, host, pod_name, container_name, filepath
O (Objects) HOST, docker_containers, kubelet_pod, host_processes HOST: host, name, state, os, arch, cpu_usage, mem_used_percent, disk_used_percent, load, cloud_provider, last_update_time
T (Traces) * (all services) or a specific service name service, resource, operation, duration (latency, usually nanoseconds or microseconds), status (ok/error), span_type (entry/local/exit), trace_id, span_id, parent_id, http_status_code, http_method, env
R (RUM) view, resource, error, action, long_task, session app_id, env, version, view_path, loading_time, lcp, fcp, fid, cls, error_message, error_type, browser, os, country, city, userid
E / UE (Events) monitor, system, custom_event df_title, df_message, df_status (critical/error/warning/info/ok), df_event_id, df_monitor_checker_name, df_dimension_tags

Not sure what data sources or fields a Workspace has? You can directly copy and execute the following metadata exploration statements (see Show Functions Reference for details): - View all Measurements: show_measurement() - View all fields in the cpu Measurement: show_field_key(from=['cpu']) - View the log source list and fields: show_source(namespace='L'), show_field(namespace='L') - View infrastructure object categories: show_source(namespace='O')

Index (index)

Indexes are an important mechanism for DQL query optimization; they can be understood as tables or partitions in traditional databases. Within a single namespace, the system may split data based on factors such as data source, data volume, and access patterns to improve query performance and management efficiency.

Role of Indexes

  • Performance optimization: Distribute data storage through indexes to reduce the amount of data scanned per query
  • Data isolation: Data from different businesses, environments, or time ranges can be stored in different indexes
  • Permission management: Different access permissions can be set for different indexes
  • Lifecycle management: Different indexes can have different data retention policies

Index Naming Rules

  • Index names can be explicitly declared; when not explicitly declared, default is used by default
  • When explicitly declaring an index name, wildcards or regular expressions are not supported for matching
  • Index names usually reflect the business attributes of the data, such as production, staging, web-logs, and api-logs

Indexes and sources are two dimensions: the same index can contain multiple sources, and a source with the same name may also appear in different indexes. In the log query L("default")::nginx, L is the namespace, default is the index name, and nginx is the source. Both single quotes and double quotes can be used for index names.

Basic Syntax

# Use the default index (automatically uses default when not specified)
M::cpu           # Equivalent to M("default")::cpu

L::nginx         # Equivalent to L("default")::nginx

# Specify a single index
M("production")::cpu     # Query CPU metrics in the production index

L("web-logs")::nginx     # Query Nginx logs in the web-logs index

# Multi-index query (query data from multiple indexes at the same time)
M("production", "staging")::cpu     # Query CPU metrics in production and staging environments

L("web-logs", "api-logs")::nginx     # Query Web and API logs

The L::nginx above is equivalent to L("default")::nginx; both query logs with source nginx in the default index. To query all sources in the default index, use L("default")::*. Whether other namespaces support custom indexes should be confirmed based on the corresponding data type and query entry point; it cannot be inferred solely from the parentheses syntax.

Indexes and Performance

Reasonable use of indexes can significantly improve query performance:

  • Precise indexes: When you know exactly which index the data is in, specify that index directly
  • Multi-index queries: When you need to query across multiple indexes, use multi-index syntax instead of wildcards
  • Avoid full-index scans: Try to reduce the data scan range through a combination of indexes and WHERE conditions

For historical reasons, DQL also supports specifying indexes in the where clause, but this is not recommended:

# Old syntax, not recommended
L::nginx { index = "web-logs" }

L::nginx { index IN ["web-logs", "api-logs"] }

For new queries, prefer explicit index declarations such as L("web-logs")::nginx, and keep business field filtering in {...}.

Application Examples

# Query the average CPU usage of each Host
M::cpu:(avg(usage)) [1h] BY host

# Query the comparison between production and staging environments
M("production", "staging")::cpu:(avg(usage)) [1h] BY index, host

# Analyze web server logs
L("web-logs")::nginx:(count(*)) {status >= 400} [1h] BY status

# Count error logs in the Web and API indexes
L("web-logs", "api-logs")::*:(count(*)) {status >= 500} [1h] BY index

Data Source (datasource)

A data source specifies the specific data source for a query and can be a dataset name, wildcard pattern, regular expression, or subquery.

Basic Data Sources

Data sources are defined differently in different namespaces:

Namespace Data Source Type Example
M Measurement cpu, memory, network
L Source nginx, tomcat, java-app
O Infrastructure object category host, container, process
T Service name user-service, order-service
R RUM data type session, view, resource, error

Data Source Syntax

Specify a Data Source Name

M::cpu:(usage)                    # Query CPU metrics

L::nginx:(count(*))                # Query Nginx logs

T::user-service:(traces)           # Query user service traces

Wildcard Matching

M::*:(usage)                      # Query all metrics

In the data source position, * selects all data sources, while the select expression :(*) selects returned fields; the two have different meanings. M::*:(usage) returns the usage field in each Measurement; it does not mean that all fields are returned automatically.

Regular Expression Matching

M::re('cpu.*'):(usage)            # Query metrics starting with cpu

L::re('web.*'):(count(*))          # Query logs starting with web

T::re('.*-service'):(traces)      # Query services ending with -service

Subquery Data Source

Subqueries are an important feature in DQL for implementing complex analysis; they allow the result of one query to be used as the data source of another query. This nested query mechanism supports multi-level analysis requirements.

Execution Mechanism

Subquery execution follows these principles:

  1. Serial execution: The inner subquery executes first, and its result is then used as the data source of the outer query
  2. Result encapsulation: Subquery results are encapsulated into a temporary table structure for use by the outer query
  3. Namespace mixing: Subqueries support mixed queries across different namespaces, enabling cross-data-type analysis
  4. Performance considerations: Subqueries increase computational complexity, so query logic should be designed reasonably

Basic Syntax

namespace::(subquery):(projections)

Execution Process

Take a typical subquery as an example:

L::(L::*:(count(*)) {level = 'error'} BY app_id):(count_distinct(app_id))

The execution process is:

  1. Inner subquery: L::*:(count(*)) {level = 'error'} BY app_id

    • Scan all log data
    • Filter out error-level logs
    • Count errors by app_id
    • Generate a temporary table: app_id | count(*)
  2. Outer query: L::(...):(count_distinct(app_id))

    • Use the subquery result as the data source
    • Count how many distinct app_ids there are
    • Final result: The number of applications with errors

Application Examples

# Count the number of applications with errors
L::(L::*:(count(*)) {level = 'error'} BY app_id):(count_distinct(app_id))

# Analyze servers with high CPU usage
M::(M::cpu:(avg(usage) AS avg_usage) [1h] BY host HAVING avg_usage > 80):(count(host))

# First find service endpoints with an error rate exceeding 1%, then count the number of affected services
M::(M::http_requests:(sum(request_count), sum(error_count)) [1h] BY service, endpoint
   HAVING sum(error_count) / sum(request_count) > 0.01
):(count_distinct(service))

Select Clause (select-clause)

The Select clause specifies the fields or expressions that a query returns and is one of the most basic and important parts of a DQL query.

Field Selection

Basic Syntax

# Select a single field
M::cpu:(usage)

# Select multiple fields
M::cpu:(usage, system, user)

# Select all fields
M::cpu:(*)

Field Name Rules

Field names can be written in the following forms:

  1. Write the name directly: Suitable for ordinary identifiers

    • ✅ message
    • ✅ host_name
    • ✅ response_time
  2. Wrap with backticks: Suitable for field names containing special characters or keywords

    • ✅ `message`
    • ✅ `limit`
    • ✅ `host-name`
    • ✅ `column with spaces`
  3. Avoid: Single quotes and double quotes wrap strings, not field names

    • ❌ 'message'
    • ❌ "message"

JSON Field Extraction

When a data field contains JSON-formatted content, you can use a subset of JSON Path syntax to extract data from inner fields.

Basic Syntax

field-name@json-path
@json-path                    // Uses the message field by default

JSON Path Syntax

  • Dot notation to access object properties: .field_name
  • Square brackets to access object properties: ["key"] (suitable for keys containing spaces or special characters)
  • Array index access: [index]

Application Examples

Assume the message field stores the following JSON text, rather than these properties already being independent log fields:

{
  "message": "User login attempt",
  "request": {
    "method": "POST",
    "path": "/api/login",
    "headers": {
      "user-agent": "Mozilla/5.0",
      "content-type": "application/json"
    },
    "body": {
      "username": "john.doe",
      "password": "***",
      "permissions": ["read", "write", "admin"]
    }
  },
  "response": {
    "status": 200,
    "time": 156,
    "data": [
      {"id": 1, "name": "user1"},
      {"id": 2, "name": "user2"}
    ]
  }
}
# Extract the request method
L::auth_logs:(message@request.method)

# Extract the request path
L::auth_logs:(message@request.path)

# Extract the username
L::auth_logs:(message@request.body.username)

# Extract the response status
L::auth_logs:(message@response.status)

# Extract User-Agent (contains hyphens, requires square brackets)
L::auth_logs:(message@request.headers["user-agent"])

# Extract the first element of the permissions array
L::auth_logs:(message@request.body.permissions[0])

# Extract the name of the first object in the response data
L::auth_logs:(message@response.data[0].name)

# Count the number of different request methods
L::auth_logs:(count(*)) [1h] BY message@request.method

# Analyze the response time distribution
L::auth_logs:(avg(message@response.time), max(message@response.time)) [1h] BY message@request.method

# Extract multiple fields
L::auth_logs:(
    message,
    message@request.method as method,
    message@request.path as path,
    message@response.status as status,
    message@response.time as response_time
) {message@response.status >= 400} [1h]

Calculated Fields

Expression Calculation

Supports basic arithmetic operations:

# Unit conversion (milliseconds to seconds)
L::nginx:(response_time / 1000 AS response_time_seconds)

# Calculate percentage
M::memory:(used / total * 100 AS usage_percentage)

# Compound calculation
M::network:((bytes_in + bytes_out) / 1024 / 1024 AS total_traffic_mb)

Function Calculation

Supports various aggregation and conversion functions:

# Aggregation functions
M::cpu:(max(usage), min(usage), avg(usage)) [1h] BY host

# Conversion functions
L::logs:(int(response_time) as response_time_seconds)

L::logs:(floor(response_time) as response_time_seconds)

Conditional Expressions

CASE WHEN is used to select different values based on conditions in a query. It is usually used with aggregation functions for conditional counting, conditional summing, or normalizing fields by condition.

Basic Syntax

CASE
  WHEN condition THEN value
  [WHEN condition THEN value ...]
  [ELSE default_value]
END

You can also use simple CASE syntax to match multiple values for the same field:

CASE field
  WHEN value1 THEN result1
  WHEN value2 THEN result2
  ELSE default_value
END

WHEN matches in the order written and returns the corresponding THEN value after the first condition is met; if none match, the ELSE value is returned. When ELSE is not explicitly written, nil is returned by default.

Application Examples

Conditional sum: Count only the traffic of 5xx requests

L::nginx_access:(
    sum(CASE WHEN status >= 500 THEN bytes ELSE 0 END) as error_bytes
) [1h] BY host

Conditional count: Count the number of error requests

L::nginx_access:(
    count(CASE WHEN status >= 500 THEN 1 ELSE nil END) as error_count
) [1h] BY service

Note: count(expr) counts non-nil values. 0 is also non-nil, so count(CASE WHEN condition THEN 1 ELSE 0 END) counts all rows, not only rows that meet the condition. For conditional counting, it is recommended to use ELSE nil, or use sum(CASE WHEN condition THEN 1 ELSE 0 END).

Multi-branch classification: Generate levels by status code

L::nginx_access:(
    max(CASE
        WHEN status >= 500 THEN 3
        WHEN status >= 400 THEN 2
        WHEN status >= 300 THEN 1
        ELSE 0
    END) as status_level
) [1h] BY service

Judge after field cleaning: Count error logs case-insensitively

L::app_logs:(
    sum(CASE WHEN lower(level) = "error" THEN 1 ELSE 0 END) as error_count
) [1h] BY service

Aggregate after type conversion: Convert a string field to a numeric value for summing

L::nginx_access:(
    sum(CASE WHEN status >= 500 THEN int(bytes) ELSE 0 END) as error_bytes
) [1h] BY host

Supported Scope

CASE WHEN is currently a restricted row-level conditional expression designed to support high-performance pushdown execution. It can be placed inside aggregation functions, such as sum(CASE ...), count(CASE ...), and max(CASE ...).

Inside CASE, the following are supported:

  • Fields
  • Literals and nil
  • Boolean conditions
  • The following scalar functions: int, float, string, md5, lower, upper, trim, ltrim, rtrim, length, regexp_replace

Aggregation functions are not supported inside CASE. Aggregation functions should be wrapped outside CASE:

# Recommended: Calculate CASE row by row first, then aggregate
L::nginx_access:(
    sum(CASE WHEN status >= 500 THEN bytes ELSE 0 END) as error_bytes
) [1h] BY host
# Not supported: Using aggregation functions inside CASE
L::nginx_access:(
    CASE WHEN sum(bytes) > 0 THEN "has_bytes" ELSE "empty" END
) [1h] BY host

Complex scalar functions not listed in the supported scope, such as regexp_extract, are also not supported inside CASE. If other complex processing is required, it is recommended to split the logic through query conditions, field cleaning, or subqueries first, to avoid triggering large-scale detail scans in CASE.

Aliases

Assign aliases to fields or expressions to make results easier to read and easier to reference later.

Basic Syntax

expression as alias_name

Application Examples

# Simple alias
M::cpu:(avg(usage) as avg_usage, max(usage) as max_usage) [1h] BY host

# Expression alias
M::memory:((used / total) * 100 as usage_percent) [1h] BY host

# Function alias
L::logs:(count(*) as error_count) {level = 'error'} [1h] BY service

# JSON extraction alias
L::api_logs:(
    message@request.method as http_method,
    message@response.status as http_status,
    message@response.time as response_time_ms
) [1h]

Usage Tips

In DQL, the result of an aggregation function can be referenced directly using the original field name, which reduces the use of aliases:

M::cpu:(max(usage)) [1h] BY host

# The result contains a max(usage) column, and the usage column name can be used directly later to obtain the `max(usage)` column of the subquery result:
M::(M::cpu:(max(usage)) [1h] BY host):(max(usage)) { usage > 80 }

But when multiple aggregation functions use the same field, aliases must be used to distinguish them correctly later:

# Cases where aliases are required
M::cpu:(max(usage) as max_usage, min(usage) as min_usage) [1h] BY host

Time Clause (time-clause)

The time clause is one of DQL's core features; it specifies the query time interval, aggregation time window, and Rollup aggregation function.

Basic Syntax

[start_time:end_time:interval:rollup]

Time Range

Absolute Timestamps

[1672502400000:1672588800000]     // Millisecond timestamp
[1672502400:1672588800]           // Second timestamp

Relative Time

Supports multiple duration units and can be mixed:

[1h]                             // Past 1 hour to now
[1h:5m]                          // From 1 hour ago to 5 minutes ago
[1h30m]                          // Past 1 hour 30 minutes
[2h15m30s]                       // Past 2 hours 15 minutes 30 seconds

Duration Expression Description

Unit Description Example
s Seconds 30s
m Minutes 5m
h Hours 2h
d Days 7d
w Weeks 4w
y Years 1y

When a duration expression is used in a time clause, it represents an offset backward from the current time. When used in a Select clause, Where clause, or other places, it is treated as a millisecond integer in calculations.

When used in aggregation queries, two additional duration units are supported:

Unit Description Example
i, is Multiple of the aggregation time window; the return value is a floating-point number of seconds 1i, 1is
ims Multiple of the aggregation time window; the return value is an integer number of milliseconds 1ims
O::HOST:(count(*)){ `last_update_time` > (now()-10m) } # 10m is treated as the integer 600,000 in calculations

L::*:( count(*) / 1i ) [::1m] # Divide by the number of seconds in the time window size (1m) to calculate the QPS of log writes

i and is represent the floating-point number of seconds of the window duration, and ims represents the integer number of milliseconds of the window duration; they depend on the current aggregation step. Ordinary duration literals participate in expressions as milliseconds; 10m cannot be treated as the numeric value 10.

Preset Time Ranges

Common time range keywords are provided:

Keyword Description Time Range
TODAY Today From today 00:00 to now
YESTERDAY Yesterday From yesterday 00:00 to today 00:00
THIS WEEK This week From this Monday 00:00 to now
LAST WEEK Last week From last Monday 00:00 to this Monday 00:00
THIS MONTH This month From the 1st of this month 00:00 to now
LAST MONTH Last month From the 1st of last month 00:00 to the 1st of this month 00:00
[TODAY]                          // Today's data
[YESTERDAY]                      // Yesterday's data
[THIS WEEK]                      // This week's data
[LAST WEEK]                      // Last week's data
[THIS MONTH]                     // This month's data
[LAST MONTH]                     // Last month's data

When using time range keywords, confirm that the Workspace time zone setting is correct and convert strictly according to the time zone requested by the user.

Time Window Aggregation

Time windows group and aggregate data by a specified time interval. The time column in the returned result represents the start time of each time window.

Single Time Window

The entire time range is aggregated into one value:

M::cpu:(max(usage_total)) [1h]

Query Result:

{
  "columns": ["time", "max(usage_total)"],
  "values": [
    [1721059200000, 37.46]
  ]
}

Time Window Aggregation

Group and aggregate by time interval:

M::cpu:(max(usage_total)) [1h::10m]

Query Result:

{
  "columns": ["time", "max(usage_total)"],
  "values": [
    [1721059200000, 37.46],
    [1721058600000, 34.12],
    [1721058000000, 33.81],
    [1721057400000, 30.92],
    [1721056800000, 34.53],
    [1721056200000, 36.11]
  ]
}

Rollup Functions

Rollup functions are an important preprocessing step in DQL; they execute before group aggregation and are used to preprocess raw time series data.

Execution Timing

The position of Rollup in the query execution flow:

Raw data → WHERE filtering → **Rollup preprocessing** → Group aggregation → HAVING filtering → Final result

Execution Mechanism

Rollup execution is divided into two stages:

  1. Per-time-series processing: Apply the Rollup function separately to each independent time series
  2. Aggregation calculation: Execute group aggregation on the results after Rollup processing

Rollup Shorthand, Rollup Function Calls, and Explicit Aggregation Calls

There are three easily confused time series function forms in DQL:

  1. Rollup shorthand: Write only the function name in the time clause, for example [rate] and [1h::5m:slope].
  2. Rollup function call: Pass algorithm parameters to the Rollup function in the time clause, for example [1h::1m:ewma(0.3)], [1h::1m:moving_average(5)], and [1h::1m:percentile(95)].
  3. Explicit aggregation call: Write a complete function call in the Select clause, for example rate(request_count), ewma(usage, 0.3), and corr(cpu_usage, request_count).

The main differences among the three forms are the execution stage and parameter capabilities:

Form Example Execution Stage Applicable Scenario
Rollup shorthand [1h::5m:rate] Before group aggregation, executed per raw time series Preprocess each time series first, then perform group aggregation
Rollup function call [1h::1m:ewma(0.3)] Before group aggregation, executed per raw time series The Rollup function requires additional algorithm parameters
Explicit aggregation call ewma(usage, 0.3) Select clause aggregation stage You need to specify fields, additional parameters, or multiple input fields

The Rollup input field in the time clause is jointly determined by the Select fields, the time window, and the raw time series, so Rollup function calls only pass additional algorithm parameters and do not pass field names in the time clause. Single-input time series functions without additional parameters can usually support Rollup shorthand; single-input functions that require additional algorithm parameters can support Rollup function calls; functions that require multiple input fields should use explicit aggregation calls.

Example: Counter metrics first Rollup, then aggregate

Counter metrics should first calculate the growth rate on each raw time series, then sum by business dimension:

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

# Not recommended: Directly aggregate the raw cumulative Counter value; the result is not QPS
M::http_requests:(sum(request_count)) [1h::5m] BY service

Example: Use Rollup function calls when additional algorithm parameters are required

ewma requires an explicit smoothing coefficient alpha. If you want to perform EWMA on each raw time series first and then enter group aggregation, you can write it in the time clause:

# Rollup function call: First perform EWMA on each time series, then average by host
M::cpu:(avg(usage)) [1h::1m:ewma(0.3)] BY host
# Error: ewma requires alpha; you cannot write only the function name
M::cpu:(avg(usage)) [1h::1m:ewma] BY host
# Error: Rollup parameters in the time clause only contain algorithm parameters, not field names
M::cpu:(avg(usage)) [1h::1m:ewma(usage, 0.3)] BY host

If you want to calculate EWMA in the Select aggregation stage, you can also use an explicit aggregation call:

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

Other single-value parameterized functions also suitable for time clause Rollup include:

# First perform a 5-point moving average on each time series, then average by host
M::cpu:(avg(usage)) [1h::1m:moving_average(5)] BY host

# First take P95 for each time series, then average by service
M::response_time:(avg(duration)) [1h::5m:percentile(95)] BY service

Example: Use explicit aggregation calls when there are multiple input fields

corr requires two input fields, so it cannot be written in time clause Rollup:

# Correct: Explicitly specify two fields in the Select clause
M::service_metric:(corr(cpu_usage, request_count)) [1h::5m] BY service
# Error: Time clause Rollup cannot express two input fields
M::service_metric:(avg(cpu_usage)) [1h::5m:corr] BY service

Example: The execution stage differs for functions with the same name

When a function supports both Rollup shorthand and explicit aggregation calls, the two forms represent different execution stages and should not be understood as completely equivalent by default:

# Rollup shorthand: First calculate zscore on each raw time series, then enter group aggregation
M::cpu:(max(usage)) [1h::5m:zscore] BY host

# Explicit aggregation call: Calculate zscore for usage in the Select aggregation stage
M::cpu:(zscore(usage)) [1h::5m] BY host

Application Scenarios

A typical application scenario for Rollup functions is Counter metric processing.

For Prometheus Counter metrics, directly aggregating raw values is meaningless because Counters are monotonically increasing. You need to calculate the growth rate for each time series first and then aggregate.

Problem example: Suppose there are request counters for two servers:

{
  "host": "web-server-01",
  "data": [
    {"time": "2024-07-15 08:25:00", "request_count": 150},
    {"time": "2024-07-15 08:20:00", "request_count": 140},
    {"time": "2024-07-15 08:15:00", "request_count": 130},
    {"time": "2024-07-15 08:10:00", "request_count": 120},
    {"time": "2024-07-15 08:05:00", "request_count": 110},
    {"time": "2024-07-15 08:00:00", "request_count": 100}
  ]
}
{
  "host": "web-server-02",
  "data": [
    {"time": "2024-07-15 08:25:00", "request_count": 250},
    {"time": "2024-07-15 08:20:00", "request_count": 240},
    {"time": "2024-07-15 08:15:00", "request_count": 230},
    {"time": "2024-07-15 08:10:00", "request_count": 220},
    {"time": "2024-07-15 08:05:00", "request_count": 210},
    {"time": "2024-07-15 08:00:00", "request_count": 200}
  ]
}

Problems with direct aggregation:

  • The initial request_count value of web-server-01 is 100
  • The initial request_count value of web-server-02 is 200
  • Although both servers have the same request rate (10 requests every 5 minutes), their absolute values are different

Solution using Rollup:

M::http:(sum(request_count)) [rate]

Execution process:

  1. Rollup stage (executed separately on each time series):

    • web-server-01: rate([100, 110, 120, 130, 140, 150]) = 2 requests/minute
    • web-server-02: rate([200, 210, 220, 230, 240, 250]) = 2 requests/minute
  2. Aggregation stage:

    • sum([2, 2]) = 4 requests/minute

Function Types

Common Rollup functions include:

Function Type Description Applicable Scenario
rate() Calculates the growth rate Counter metrics
increase() Calculates the increase Counter metrics
last() Takes the last value Gauge metrics
avg() Calculates the average value Data smoothing
max() Takes the maximum value Peak analysis
min() Takes the minimum value Trough analysis

But almost all aggregation functions that return a single value can be used, so the full function list is not listed here.

Default Rollup

If no Rollup function is explicitly specified, DQL does not perform Rollup calculation by default. PromQL's default Rollup is last, so if you are calculating Prometheus metrics, be sure to understand this difference and specify the Rollup function manually.

Application Examples

# Calculate the total request rate of all servers
M::http_requests:(sum(request_count)) [rate]

# Calculate the error rate
M::http_requests:(
    sum(error_count) as errors,
    sum(request_count) as requests
) [rate] BY service

Flexible Time Window Syntax

DQL supports shorthand formats for various time windows, making queries easier to write.

Shorthand Formats

[1h]                             // Specify only the time range
[1h::5m]                         // Time range + aggregation step
[1h:5m]                          // Start time + end time
[1h:5m:1m]                       // Start + end + step
[1h:5m:1m:avg]                   // Complete format
[::5m]                           // Specify only the aggregation step
[:::sum]                         // Specify only the rollup function
[sum]                            // Specify only the rollup function (simplest form)

Time Shift (SHIFT)

SHIFT shifts the entire query time window forward as a whole, reading data from the specified duration ago; the time column of the result still displays the current window:

<select-query> SHIFT <duration>

SHIFT follows the time window and is located before clauses such as BY, HAVING, and ORDER BY:

L::logs:(service, count(*) AS requests)[1d:1h] SHIFT 7d BY service

Filtering, grouping, aggregation, sorting, and pagination are all executed based on the data before the shift; the result structure is the same as a query without SHIFT, except that the time column still falls within the current window. duration must be a positive fixed duration, such as 1h or 7d.

Nested SELECT queries can each declare a query-level SHIFT, and offsets are stacked by level. Query-level SHIFT can be combined with expression-level SHIFT (see SHIFT in the DQL Functions Reference): the query-level offset first determines the baseline window for the entire query, and the expression-level offset then reads earlier aggregated values relative to that baseline window.

Where Clause (where-clause)

The where clause filters data rows, retaining only data that meets the conditions for subsequent processing.

Basic Syntax

{condition1, condition2, condition3}

Multiple conditions can be connected with commas, AND, OR, &&, or ||.

Comparison Operators

Operator Description Example
= Equal to host = 'web-01'
!= Not equal to status != 200
> Greater than cpu_usage > 80
>= Greater than or equal to memory_usage >= 90
< Less than response_time < 1000
<= Less than or equal to disk_usage <= 80

Pattern Matching Operators

Operator Description Example
=~ Regex match message =~ 'error.*\\d+'
!~ Regex not match message !~ 'debug.*'

Set Operators

Operator Description Example
IN In a set status IN [200, 201, 202]
NOT IN Not in a set level NOT IN ['debug', 'info']

Logical Operators

Operator Description Example
AND or && Logical AND cpu > 80 AND memory > 90
OR or \|\| Logical OR status = 500 OR status = 502
NOT Logical NOT NOT status = 200

Tip: In addition to performing logical OR, the OR operator also provides null fallback semantics: when the left expression returns NULL, it directly returns the result of the right expression. This can be used to implement priority fallback logic, for example status OR backup_status.

Application Examples

Basic Filtering

# Single condition
M::cpu:(usage) {host = 'web-01'} [1h]

# Multiple AND conditions
M::cpu:(usage) {host = 'web-01', usage > 80} [1h]

# Use the AND keyword
M::cpu:(usage) {host = 'web-01' AND usage > 80} [1h]

# Mix logical operators
M::cpu:(usage) {(host = 'web-01' OR host = 'web-02') AND usage > 80} [1h]

Regular Expression Matching

# Match error logs
L::logs:(message) {message =~ 'ERROR.*\\d{4}'} [1h]

# Match logs in a specific format
L::logs:(message) {message =~ '\\[(ERROR|WARN)\\].*'} [1h]

# Exclude debug information
L::logs:(message) {message !~ 'DEBUG.*'} [1h]

# Hostname pattern matching
M::cpu:(usage) {host =~ 'web-.*\\.prod\\.com'} [1h]

Set Operations

# Status code filtering
L::nginx:(count(*)) {status IN [200, 201, 202, 204]} [1h]

# Exclude specific status codes
L::nginx:(count(*)) {status NOT IN [404, 500, 502]} [1h]

# Log level filtering
L::app_logs:(count(*)) {level IN ['ERROR', 'WARN', 'CRITICAL']} [1h]

Handling Array Fields

When the field type is an array (for example, the tag array field df_label or labels of the Host object O::HOST), DQL supports inclusive matching of array elements.

Assume the array field of a row is df_label = ['web', 'prod', 'api']:

Using IN [...] on an array field means the array contains any one element of the right-side list (the intersection is non-empty); NOT IN [...] means the array does not contain any element of the right-side list.

// Check whether the array contains the specified value
{df_label IN ['web']}                  // true, because df_label contains 'web'
{df_label IN ['mobile']}               // false, because df_label does not contain 'mobile'

// When multiple values are passed: as long as any one of them is contained, it is true (logical OR)
{df_label IN ['web', 'mobile']}        // true, because it contains 'web'

// Check whether the array does not contain any value in the list
{df_label NOT IN ['mobile', 'dev']}    // true, because it contains neither 'mobile' nor 'dev'
{df_label NOT IN ['web', 'mobile']}    // false, because it contains 'web'

If you need to require the array to contain multiple specified tags at the same time (logical AND), you can combine multiple IN conditions with AND (or commas):

# Query the list of Host objects with the 'prod' tag
O::HOST:(host, cpu_usage, mem_used_percent, df_label) {df_label IN ['prod']} LIMIT 20

# Query the list of Host objects with both the 'web' and 'prod' tags
O::HOST:(host, cpu_usage, mem_used_percent, df_label) {df_label IN ['web'], df_label IN ['prod']} LIMIT 20

The following = / != syntax is retained for historical compatibility and is not recommended for new queries (on array fields, = means containing all right-side elements, and != means not containing any right-side element, which differs from the equality semantics of ordinary scalar fields and is easy to confuse):

// Historical syntax: Single-value inclusion check (overloaded equality operator semantics)
{df_label = 'web'}           // true, because df_label contains 'web'
{df_label != 'mobile'}       // true, because df_label does not contain 'mobile'

Function Filtering

Any function that returns a Boolean value can be used as a filter condition.

# String matching
L::logs:(message) { match(message, 'error') }

L::logs:(message) { wildcard(message, 'error*') }

# Query requests with abnormal response time
L::access_logs:(*) {
    response_time > 1000 AND
    match(message, 'timeout')
}

# Query Hosts with abnormal memory usage
M::memory:(usage) {
    (usage > 90 OR usage < 10) AND
    host =~ 'prod-.*' AND
    tags IN ['critical', 'important']
}

Full-Text Search and Tokenization Rules

When using search(...) or query_string(...) for full-text search in the WHERE clause, the system first splits the original text and query conditions into independent tokens, and then performs fast matching by token. Understanding tokenization rules helps you accurately determine which data a query will match, and choose the appropriate function when you need to precisely match symbols or substrings.

For query paths that use full-text tokenization, you can refer to the following rules. Matching behavior also depends on the storage engine; see query_string for related differences.

1. Core Splitting Rules

The tokenizer processes characters in text according to the following three types of rules (case-insensitive by default):

Character Type Splitting Rule Example (Original Text → Tokens)
English letters and digits Consecutive English letters (a-z, A-Z) and digits (0-9) are merged into the same token and converted to lowercase Error → error
http2 → http2
v1_2 → v1, 2
Chinese characters Split into independent tokens according to common Chinese phrases or single characters 连接超时 → 连接, 超时
数据库异常 → 数据库, 异常
Whitespace and punctuation Spaces, tabs, newlines, and all common punctuation marks are used as separators, splitting the tokens on both sides during tokenization; they are not themselves independent tokens user_name → user, name
api.example.com → api, example, com
host-01:8080 → host, 01, 8080

Common separators and their splitting effects are as follows:

Symbol Category Characters Included Typical Scenario Example (Original Text → Tokenization Result)
Whitespace characters Spaces, \t, \n error timeout → error, timeout
Connectors and underscores _, - user_name → user, name
kube-system → kube, system
Dots and colons ., : 192.168.1.1:8080 → 192, 168, 1, 1, 8080
app.service:prod → app, service, prod
Path and URL symbols /, ?, =, &, # /api/v1/users?id=42 → api, v1, users, id, 42
Email and other punctuation @, ,, ;, ', ", (, ), [, ], {, }, etc. admin@example.com → admin, example, com

2. Typical Text Tokenization Examples

  • URL address: https://api.example.com/v1/users?id=123&env=prod_01 → Tokenized as: https, api, example, com, v1, users, id, 123, env, prod, 01
  • Email and hostname: user_admin@mail-server.example.com → Tokenized as: user, admin, mail, server, example, com
  • Mixed Chinese and English logs: [ERROR] order_service: 订单支付失败, code=500 → Tokenized as: error, order, service, 订单, 支付, 失败, code, 500

3. Keyword Matching vs Phrase Matching

When a query condition is split into multiple tokens, different forms determine how these tokens are combined:

Match Mode Syntax Example Actual Matching Logic Text That Will Match Text That Will Not Match
Keyword matching (default) search("connection timeout")
query_string("connection timeout")
The target text contains all tokens at the same time (AND relationship), regardless of order or distance "connection timeout"
"timeout: connection reset"
Text that contains only "connection" but not "timeout"
Phrase matching (adjacent and in order) search("#\"build error\"")
query_string("\"build error\"")
Tokens must appear adjacent in order (only spaces or punctuation are allowed between tokens) "build error"
"build: error"
"build succeeded, parse error" (other tokens are in between)
"error during build" (reverse order)

Note: Because punctuation marks such as ., _, -, @, and / are all treated as separators during tokenization, phrase matching only checks whether tokens are adjacent in order, and does not distinguish which specific punctuation mark is between tokens. For example, search("#\"user_name\"") or query_string("\"user_name\"") will match both user_name and user-name or user.name.

4. Text Matching Function Selection Recommendations

Query Requirement Recommended Form Reason
Search for complete words or phrases (case-insensitive) search("error timeout")
search("#\"connection reset\"")
Uses the tokenization index directly, providing the fastest query speed
Boolean combination search (contains A or B, and does not contain C) query_string("(error OR warn) AND NOT timeout") Supports AND, OR, NOT, and parenthesized grouping
Strictly match substrings containing punctuation (for example, distinguish user_name from user-name, or precisely find /api/v1/login) match(message, "user_name")
match(message, "/api/v1/login")
match performs character-by-character substring inclusion matching on the original text, and will not ignore symbol differences due to tokenization of _, /, or .
Match fragments inside words (for example, use cept to match Exception) match(message, "cept")
wildcard(message, "*cept*")
Tokenization-based search uses complete tokens as units; search("cept") will not match Exception; substring or wildcard matching is required
Case-sensitive or match complex formats (such as 4-digit error codes) re(message, "ERR-\\d{4}") re / regexp supports full regular expressions and is case-sensitive
# 1. Full-text token search: Contains both error and timeout (case-insensitive and order-independent)
L::*:(service, message) {search("error timeout")} [15m] LIMIT 20

# 2. Phrase order search: build and error must appear adjacent in order
L::*:(service, message) {search("#\"build error\"")} [15m] LIMIT 20

# 3. Strict substring matching: Precisely match "user_name" containing an underscore; it will not mistakenly match "user-name"
L::*:(service, message) {match(message, "user_name")} [15m] LIMIT 20

# 4. Combined logical search: Contains error or warn, and does not contain healthcheck
L::*:(service, message) {query_string("(error OR warn) AND NOT healthcheck")} [15m] LIMIT 20

WHERE Subquery

The WHERE subquery is a powerful feature in DQL for implementing dynamic filtering; it allows the result of one query to be used as the filter condition of another query. This mechanism supports dynamic filtering based on data analysis results.

Query Characteristics

  • Dynamic filtering: The filter condition is not a fixed value but is dynamically calculated through a query
  • Namespace mixing: Supports queries across namespaces, enabling correlation analysis of different data types
  • Serial execution: The subquery executes first, and its result is used for filtering in the main query
  • Single-column result: The inner subquery selects only one dimension field; after deduplication, the result is used as the filter value for the outer IN or NOT IN

Execution Flow

Take a typical WHERE subquery as an example:

M::cpu:(avg(usage)) { host IN (O::HOST:(hostname) {provider = 'cloud-a'}) } [1h] BY host

Execution process:

  1. Subquery execution: O::HOST:(hostname) {provider = 'cloud-a'}

    • Query all infrastructure objects
    • Filter out Hosts whose provider is 'cloud-a'
    • Return the hostname list: ['host-01', 'host-02', 'host-03']
  2. Main query execution: M::cpu:(avg(usage)) [1h] BY host {host IN [...]}

    • Query CPU usage data
    • Count only the Hosts returned by the subquery
    • Calculate average usage grouped by Host

Application Examples

# Monitor servers of a specific cloud provider
M::cpu:(avg(usage)) { host IN (O::HOST:(hostname) {provider = 'cloud-a'}) } [1h] BY host

# Compare performance of different cloud providers
M::memory:(avg(used / total * 100)) { host IN (O::HOST:(hostname) {provider IN ['cloud-a', 'cloud-b']}) } [1h] BY host

# Analyze logs of a specific business
L::app_logs:(count(*)) { service IN (T::services:(service_name) {business_unit = 'ecommerce'}) } [1h] BY level

# Monitor application performance of critical businesses
M::response_time:(avg(response_time)) { service IN (T::services:(service_name) {criticality = 'high'}) } [1h] BY service

Group By Clause (group-by-clause)

Grouping is a core function of data analysis, used to group and aggregate data by specified dimensions.

Basic Syntax

BY expression1, expression2, ...

Grouping Types

Field Grouping

# Single-field grouping
M::cpu:(avg(usage)) [1h] BY host

# Multi-field grouping
M::cpu:(avg(usage)) [1h] BY host, env

# Nested grouping
M::cpu:(avg(usage)) [1h] BY datacenter, rack, host

Expression Grouping

# Compound mathematical expression
M::memory:(avg(used)) [1h] BY ((used / total) * 100) as
usage_percent

# Multi-field mathematical operation
M::performance:(avg(response_time)) [1h] BY
(response_time / 1000) as response_seconds

Function Grouping

# Drain clustering algorithm
L::logs:(count(*)) BY drain(message, 0.7) as sample

# Regex extraction grouping
L::logs:(count(*)) [1h] BY regexp_extract(message, 'error_code: (\\d+)', 1)

Group Result Handling

When a query contains both grouping and a time window, a two-dimensional data structure is produced. Group By can be used together with a time window; the query result will then be a two-dimensional array. The first dimension of this two-dimensional array consists of multiple groups distinguished by group keys, and the second dimension is the multi-time-interval data within a single group.

Example of a two-dimensional data structure:

Query: M::cpu:(max(usage_total)) [1h::10m] by host

Query Result Structure:

{
  "series": [
    {
      "columns": ["time", "max(usage_total)"],
      "name": "cpu",
      "tags": {"host": "web-server-01"},
      "values": [
        [1721059200000, 78.5],
        [1721058600000, 82.3],
        [1721058000000, 75.8],
        [1721057400000, 88.2]
      ]
    },
    {
      "columns": ["time", "max(usage_total)"],
      "name": "cpu",
      "tags": {"host": "web-server-02"},
      "values": [
        [1721059200000, 45.2],
        [1721058600000, 52.8],
        [1721058000000, 48.5],
        [1721057400000, 61.3]
      ]
    },
    {
      "columns": ["time", "max(usage_total)"],
      "name": "cpu",
      "tags": {"host": "web-server-03"},
      "values": [
        [1721059200000, 92.1],
        [1721058600000, 95.7],
        [1721058000000, 89.4],
        [1721057400000, 97.6]
      ]
    }
  ]
}

The values above show only some time points. Group sorting needs to calculate sorting values based on the entire query window; you should not use only the displayed fragment to recalculate statistics for the complete window.

Processing this two-dimensional array again:

  1. To filter the results of this two-dimensional array, use the Having clause.
  2. To sort or paginate data within a single group in the two-dimensional array, use the order by, limit, and offset series of statements.
  3. To sort or paginate the groups of the two-dimensional array, use the sorder by, slimit, and soffset series of statements.

For detailed information about the two-dimensional data structure and sorting and pagination features, see Sorting and Pagination.

HAVING Clause (having-clause)

The Having clause filters the results after group aggregation, similar to the WHERE clause, but it acts on aggregated data.

Basic Syntax

HAVING condition

Difference from WHERE

WHERE and HAVING are both clauses used to filter data, but they take effect at different stages of query execution and handle different filter conditions.

Difference in Execution Timing

Raw data → WHERE filtering → Group aggregation → HAVING filtering → Final result
  1. WHERE clause:

    • Executes before group aggregation
    • Acts on raw data rows
    • Filters out data rows that do not meet the conditions, reducing the amount of data for subsequent processing
  2. HAVING clause:

    • Executes after group aggregation
    • Acts on aggregated results
    • Filters based on the results of aggregation functions

Application Scenarios

The HAVING clause is suitable for filtering aggregated results:

# Filtering based on aggregation function values
M::cpu:(avg(usage) as avg_usage) [1h] BY host HAVING avg_usage > 80

# Filtering based on multiple aggregation conditions
M::http_requests:(
    sum(request_count) as total,
    sum(error_count) as errors
) [1h] BY service, endpoint
HAVING errors / total > 0.01 AND total > 1000

# Filtering based on group statistics
L::logs:(count(*) as count) [1h] BY service HAVING count > 100

# Filtering based on compound aggregation conditions
M::response_time:(
    avg(response_time) as avg_time,
    max(response_time) as max_time,
    min(response_time) as min_time
) [1h] BY endpoint
HAVING avg_time > 1000 AND max_time > 5000 AND (max_time - min_time) > 2000

Sorting and Pagination

Sorting and pagination in DQL are very important and unique features. They are designed with a dual sorting mechanism based on the characteristics of time series data: intra-group sorting and inter-group sorting. This design enables DQL to efficiently handle complex multi-dimensional time series data analysis requirements.

Understanding the Data Structure of DQL

Before diving into sorting and pagination, let's understand the two-dimensional data structure of DQL query results. When a query contains both grouping (BY) and a time window, a two-dimensional array is produced:

  • First dimension (group dimension): Multiple groups distinguished by group keys
  • Second dimension (time dimension): Data aggregated by time window within each group

For detailed information about the two-dimensional data structure and JSON format examples, see Group Result Handling. This two-dimensional structure is the foundation of DQL sorting and pagination; understanding it is essential for mastering DQL's sorting mechanism.

Intra-Group Sorting and Pagination (ORDER BY, LIMIT, OFFSET)

Intra-group sorting and pagination act on the second dimension of the two-dimensional structure, that is, the data within each group. This sorting is executed independently within each group and does not affect data in other groups.

Basic Syntax

ORDER BY expression [ASC|DESC]
LIMIT row_count
OFFSET row_offset

Execution Mechanism

The execution process of intra-group sorting:

  1. Group processing: Execute the sorting operation independently for each group
  2. Sorting basis: You can use time fields, aggregation function results, or calculated expressions
  3. Pagination limit: LIMIT limits the number of data rows returned per group
  4. Offset handling: OFFSET skips the first N rows of data in each group

Application Examples

Basic Time Sorting
# Sort by time in descending order and display the latest data for each Host
M::cpu:(max(usage_total)) [1h::10m] BY host ORDER BY time DESC

# Sort by time in ascending order and display historical trends
M::cpu:(max(usage_total)) [1h::10m] BY host ORDER BY time ASC

Execution Result (ORDER BY time DESC):

{
  "series": [
    {
      "columns": ["time", "max(usage_total)"],
      "name": "cpu",
      "tags": {"host": "web-server-01"},
      "values": [
        [1721059200000, 78.5],  // 12:00:00
        [1721058600000, 82.3],  // 11:50:00
        [1721058000000, 75.8],  // 11:40:00
        [1721057400000, 88.2],  // 11:30:00
        [1721056800000, 72.1],  // 11:20:00
        [1721056200000, 69.4]   // 11:10:00
      ]
    },
    {
      "columns": ["time", "max(usage_total)"],
      "name": "cpu",
      "tags": {"host": "web-server-02"},
      "values": [
        [1721059200000, 45.2],  // 12:00:00
        [1721058600000, 52.8],  // 11:50:00
        [1721058000000, 48.5],  // 11:40:00
        [1721057400000, 61.3],  // 11:30:00
        [1721056800000, 55.7],  // 11:20:00
        [1721056200000, 58.9]   // 11:10:00
      ]
    }
  ]
}
Sorting Based on Values
# Sort by CPU usage in descending order to find the peak period for each Host
M::cpu:(max(usage_total) as max_usage_total) [1h::10m] BY host ORDER BY max_usage_total DESC

# Sort by response time in ascending order to find the period with the best performance
M::response_time:(avg(response_time) as avg_response_time) [1h::5m] BY endpoint ORDER BY avg_response_time ASC
Intra-Group Pagination
# Display only the latest 3 data points for each Host
M::cpu:(max(usage_total)) [1h::10m] BY host ORDER BY time DESC LIMIT 3

# Skip the latest 2 data points and display the next 3
M::cpu:(max(usage_total)) [1h::10m] BY host ORDER BY time DESC LIMIT 3 OFFSET 2

Execution Result (LIMIT 3):

{
  "series": [
    {
      "columns": ["time", "max(usage_total)"],
      "name": "cpu",
      "tags": {"host": "web-server-01"},
      "values": [
        [1721059200000, 78.5],  // 12:00:00 - latest
        [1721058600000, 82.3],  // 11:50:00
        [1721058000000, 75.8]   // 11:40:00
        // Only the first 3 records are returned
      ]
    },
    {
      "columns": ["time", "max(usage_total)"],
      "name": "cpu",
      "tags": {"host": "web-server-02"},
      "values": [
        [1721059200000, 45.2],  // 12:00:00 - latest
        [1721058600000, 52.8],  // 11:50:00
        [1721058000000, 48.5]   // 11:40:00
        // Only the first 3 records are returned
      ]
    }
  ]
}

Inter-Group Sorting and Pagination (SORDER BY, SLIMIT, SOFFSET)

Inter-group sorting and pagination are distinctive DQL features; they act on the first dimension of the two-dimensional structure, that is, sorting the groups (Series) themselves and taking Top-N.

When a query does not use BY, the result usually has only one group. In this case, SORDER BY usually has no visible effect on sorting, but SLIMIT / SOFFSET still take effect according to the "number of groups" semantics (that is, targeting that single group).

Basic Syntax

SORDER BY alias_or_aggregate [ASC|DESC]
SLIMIT group_count
SOFFSET group_offset

Execution Mechanism and Core Semantics

The execution process of inter-group sorting:

  1. Determine the sorting representative value for each group:
    • Single-window aggregation query (without a step, such as [1h]): Each group has only one row of aggregation results, and SORDER BY <projection alias> directly sorts groups by that aggregation value.
    • Multi-time-point time series query (with a step, such as [1h::5m]): Each group has multiple time buckets. SORDER BY <projection alias> sorts by the value of the last time bucket (last) of that group; SORDER BY sum(<projection alias>) / avg(<projection alias>) / max(<projection alias>) sorts by performing a secondary aggregation on all time buckets of that projection column across the entire query period.
  2. Group sorting: Sort all groups in ascending or descending order according to the representative value of each group.
  3. Group pagination: SLIMIT limits the number of groups returned (an explicitly specified value must be a positive integer); SOFFSET skips the first N groups.

Important Tips (Recommended Specification for Writing SORDER BY): 1. Always assign an alias to the Select aggregation expression and reference that alias in SORDER BY (for example, M::cpu:(avg(usage_total) AS avg_usage) [1h] BY host SORDER BY avg_usage DESC SLIMIT 5). Do not directly write unaliased aggregations or raw fields in SORDER BY (such as SORDER BY count(*) or SORDER BY avg(usage_total)), because SORDER BY executes after projection; at that point the original columns no longer exist and cannot be pushed down. 2. How should you choose the sorting method for time series queries with a step? - Sort by the latest time bucket: Directly write SORDER BY avg_usage DESC. - Sort by the sum/average/peak over the entire period: Apply an aggregation function to the projection alias, for example M::cpu:(avg(usage_total) AS avg_usage) [1h::5m] BY host SORDER BY avg(avg_usage) DESC SLIMIT 5 (or use WHERE ... IN (subquery) to first select the Top-N dimensions in a single-bucket window [1h::1h]).

Choosing Dimension Reduction Functions

For queries with a step, you can choose the representative value according to the sorting goal. If no aggregation function is specified, the value of the last time bucket is used.

Commonly used dimension reduction functions include:

Function Description Applicable Scenario
last() Takes the last value Suitable for the current state of a time series
max() Takes the maximum value Suitable for peak analysis
min() Takes the minimum value Suitable for trough analysis
avg() Takes the average value Suitable for overall trend analysis
sum() Sums values Suitable for total statistics
count() Counts values Suitable for frequency analysis

But almost all aggregation functions that return a single value can be used; the full function list is not detailed here.

Application Examples

Single-Window Leaderboard (Sorted by Aggregated Value for the Entire Period)
# Find the top 5 Hosts with the highest average CPU usage in the past 1 hour
M::cpu:(avg(usage_total) AS avg_usage) [1h] BY host SORDER BY avg_usage DESC SLIMIT 5

# Find the 10 APM services with the shortest average response latency in the past 1 hour
T::*:(avg(duration) AS avg_duration) [1h] BY service SORDER BY avg_duration ASC SLIMIT 10

# Find the top 5 services with the most error logs in the past 1 hour
L::*:(count(*) AS error_count) {status = 'error'} [1h] BY service SORDER BY error_count DESC SLIMIT 5
Multi-Time-Point Time Series Query (Sorted by Latest Time Bucket)
# Query the peak CPU of each Host in the past 1 hour (one point every 10 minutes), and get the top 10 Hosts in descending order by the peak value in the latest time bucket
M::cpu:(max(usage_total) AS max_usage) [1h::10m] BY host SORDER BY max_usage DESC SLIMIT 10

# Query the minimum memory usage of each Host in the past 24 hours (one point every 1 hour), and get the 5 Hosts with the lowest values in the latest time bucket
M::mem:(min(used_percent) AS min_mem) [24h::1h] BY host SORDER BY min_mem ASC SLIMIT 5

Execution Result Example (SLIMIT 2):

{
  "series": [
    {
      "columns": ["time", "avg_usage"],
      "name": "cpu",
      "tags": {"host": "web-server-03"},
      "values": [
        [1721059200000, 92.1],
        [1721058600000, 95.7],
        [1721058000000, 89.4]
      ]
    },
    {
      "columns": ["time", "avg_usage"],
      "name": "cpu",
      "tags": {"host": "web-server-01"},
      "values": [
        [1721059200000, 78.5],
        [1721058600000, 82.3],
        [1721058000000, 75.8]
      ]
    }
  ]
}

Combined Use of Dual Sorting and Pagination

In practical applications, intra-group sorting and inter-group sorting are often used together to meet complex data display requirements. This combination can control both the order of groups and the order of data within groups.

Execution Order

Understand from the two dimensions of result display: first determine which groups need to be returned, and then determine which data points each group displays; this is not equivalent to specifying the engine's physical execution plan. When writing statements, place ORDER BY, LIMIT, and OFFSET before SORDER BY, SLIMIT, and SOFFSET:

  1. Inter-group sorting: First sort and paginate all groups
  2. Intra-group sorting: Perform internal sorting and pagination on the selected groups

Application Examples

Monitoring Dashboard Scenario
# Find the 10 servers with the highest CPU usage and display the latest 5 data points for each
M::cpu:(avg(usage_total) AS avg_usage) [1h::10m] BY host
ORDER BY time DESC LIMIT 5                 # Display the latest 5 data points for each Host
SORDER BY avg(avg_usage) DESC SLIMIT 10    # Sort by the average value of each time bucket over the entire period

Execution Result:

{
  "series": [
    {
      "columns": ["time", "avg(usage)"],
      "name": "cpu",
      "tags": {"host": "web-server-03"},  // Average usage: 90.9 - ranked first
      "values": [
        [1721059200000, 92.1],  // 12:00:00 - latest
        [1721058600000, 95.7],  // 11:50:00
        [1721058000000, 89.4],  // 11:40:00
        [1721057400000, 97.6],  // 11:30:00
        [1721056800000, 87.3]   // 11:20:00
        // Only the latest 5 data points are returned (LIMIT 5)
      ]
    },
    {
      "columns": ["time", "avg(usage)"],
      "name": "cpu",
      "tags": {"host": "web-server-01"},  // Average usage: 77.7 - ranked second
      "values": [
        [1721059200000, 78.5],  // 12:00:00 - latest
        [1721058600000, 82.3],  // 11:50:00
        [1721058000000, 75.8],  // 11:40:00
        [1721057400000, 88.2],  // 11:30:00
        [1721056800000, 72.1]   // 11:20:00
        // Only the latest 5 data points are returned (LIMIT 5)
      ]
    }
    // Other Hosts are filtered out because SLIMIT 10 returns only the top 10 by usage
  ]
}

By mastering DQL's sorting and pagination features, you can build powerful monitoring dashboards, performance analysis tools, and business insight systems.

Note

Using a reasonable combination of intra-group sorting and inter-group sorting can greatly improve the efficiency and effectiveness of data analysis.

Common Query Scenarios in Practice

The following templates apply to infrastructure monitoring, log troubleshooting, trace analysis, RUM analysis, and event statistics. After replacing Measurements, sources, and fields with the actual names in the Workspace, you can use them in the Query Workbench.

Scenario 1: Infrastructure Monitoring (Host CPU / Memory / Disk / Network)

  • Data prerequisites: DataKit is installed and the default Host collectors are enabled (cpu, mem, disk, net, system, and the object O::HOST).
  • Expected results: Return resource utilization rankings, time series trends, or online Host lists grouped by Host or device.
# 1.1 Query the top 10 Hosts with the highest average CPU usage in the past 1 hour (single-value ranking)
M::cpu:(avg(usage_total) AS avg_cpu, max(usage_total) AS max_cpu) [1h] BY host SORDER BY avg_cpu DESC SLIMIT 10

# 1.2 View the time series trend of Hosts with memory usage exceeding 80% (one point every 5 minutes)
M::mem:(avg(used_percent) AS mem_pct) [1h::5m] BY host HAVING mem_pct > 80 SORDER BY mem_pct DESC SLIMIT 20

# 1.3 Query disk partition usage and free space for each Host (unit converted to GB)
M::disk:(last(used_percent) AS disk_pct, last(free) / 1024 / 1024 / 1024 AS free_gb) [15m] BY host, device HAVING disk_pct > 75 SORDER BY disk_pct DESC SLIMIT 20

# 1.4 Calculate inbound and outbound throughput rates for each Host NIC (Counter metrics use rate to convert to bytes/second)
M::net:(sum(bytes_recv) AS recv_bps, sum(bytes_sent) AS sent_bps) [1h::1m:rate] BY host SORDER BY recv_bps DESC SLIMIT 10

# 1.5 View the list of online Linux Host assets and core load metrics in the last 10 minutes
O::HOST:(host, os, arch, cpu_usage, mem_used_percent, disk_used_percent, load) {os = 'linux', last_update_time > now() - 10m} ORDER BY cpu_usage DESC LIMIT 20

Scenario 2: Log Search and Troubleshooting (Logging)

  • Data prerequisites: Log collection is enabled (L namespace, including common fields message, status, service, source, and host).
  • Expected results: Return error log trends, high-frequency error services, log clustering templates, or context desensitization extraction results.
# 2.1 Search error log details containing "timeout" or "connection refused" in the last 15 minutes
L::*:(source, service, host, status, message) {status IN ['error', 'critical'], query_string(message, "timeout OR \"connection refused\"")} [15m] ORDER BY time DESC LIMIT 50

# 2.2 Count log write QPS (log records per second) by service in the last 1 hour
L::*:(count(*) / 1i AS log_qps) [1h::1m] BY service SORDER BY log_qps DESC SLIMIT 10

# 2.3 Count the number of error logs and total logs for each service, and filter services with more than 10 error logs
L::*:(
    count(*) AS total_logs,
    count(CASE WHEN status = 'error' OR status = 'critical' THEN 1 ELSE nil END) AS error_logs
) [1h] BY service HAVING error_logs > 10 SORDER BY error_logs DESC SLIMIT 20

# 2.4 Use the Drain algorithm to automatically cluster error logs in the last 1 hour and quickly locate high-frequency error patterns
L::*:(count(*) AS cnt, any(service) AS sample_service) {status = 'error'} [1h] BY drain(message, 0.7) AS log_template SORDER BY cnt DESC SLIMIT 20

Scenario 3: APM Application Performance and Trace Analysis (Tracing)

  • Data prerequisites: APM distributed tracing has been ingested (T namespace, including the standard fields service, resource, duration, status, span_type, and trace_id).
  • Expected results: Return service throughput, error rate, P50/P95/P99 response latency, and slow call details.
# 3.1 Count P50 / P95 / P99 response latency for service entry requests (span_type = 'entry') (unit: nanoseconds)
T::*:(
    p50(duration) AS p50_ns,
    p95(duration) AS p95_ns,
    p99(duration) AS p99_ns
) {span_type = 'entry'} [1h] BY service SORDER BY p99_ns DESC SLIMIT 15

# 3.2 Count the total number of requests, number of errors, and error rate percentage for each service
T::*:(
    count(*) AS total_req,
    count(CASE WHEN status = 'error' THEN 1 ELSE nil END) AS err_req,
    (count(CASE WHEN status = 'error' THEN 1 ELSE nil END) / count(*)) * 100 AS err_rate_pct
) {span_type = 'entry'} [1h] BY service SORDER BY err_req DESC SLIMIT 15

# 3.3 Analyze the latency distribution histogram and percentiles for a single endpoint (histogram_auto)
T::*:(histogram_auto(duration)) {span_type = 'entry'} [1h] BY service SLIMIT 10

# 3.4 Search details of the top 20 abnormal call chains with the longest duration in the last 15 minutes
T::*:(service, resource, duration, http_status_code, trace_id, span_id) {status = 'error'} [15m] ORDER BY duration DESC LIMIT 20

Scenario 4: RUM User Experience Analysis (Real User Monitoring)

  • Data prerequisites: Frontend or mobile RUM collection has been ingested (R namespace, including data sources view, error, and resource).
  • Expected results: Return page PV/UV, first-screen loading time, and frontend JS error rankings.
# 4.1 Count page views (PV), unique visitors (UV), and average loading time for each page in the past 24 hours
R::view:(
    count(*) AS pv,
    count_distinct(userid) AS uv,
    avg(loading_time) AS avg_load_time
) [24h] BY view_path SORDER BY pv DESC SLIMIT 20

# 4.2 Count the error types with the most frontend errors and sample messages in the past 1 hour
R::error:(count(*) AS err_cnt, any(error_message) AS sample_msg) [1h] BY app_id, error_type SORDER BY err_cnt DESC SLIMIT 15

Scenario 5: Year-over-Year / Period-over-Period Analysis and Unrecovered Alert Query

  • Data prerequisites: The Workspace has historical data for the same period (for SHIFT comparison) or Monitor alerts are enabled (E / UE namespaces).
  • Expected results: Return comparison results between the current window and the same period yesterday/last week, or statistics on current unrecovered alerts.
# 5.1 Week-over-week log traffic analysis: Compare the log volume and growth multiple of each service in the past 1 hour and the same period 7 days ago
L::*:(
    service,
    count(*) AS current_logs,
    count(*) SHIFT 7d AS last_week_logs,
    CASE
        WHEN (count(*) SHIFT 7d) = nil OR (count(*) SHIFT 7d) = 0 THEN nil
        ELSE count(*) / (count(*) SHIFT 7d)
    END AS wow_ratio
) [1h] BY service SLIMIT 15

# 5.2 Query current unrecovered alert events (UE namespace) grouped by alert level and Monitor
UE::monitor:(count(*) AS active_events, any(df_title) AS sample_title) [24h] BY df_status, df_monitor_checker_name SORDER BY active_events DESC SLIMIT 20

By mastering DQL's sorting, pagination, and combined analysis capabilities, you can build powerful monitoring dashboards, performance analysis tools, and business insight systems.

Note

Using a reasonable combination of intra-group sorting and inter-group sorting can greatly improve the efficiency and effectiveness of data analysis.

Feedback

Is this page helpful?