> ## Documentation Index
> Fetch the complete documentation index at: https://docs.struct.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Query language

> Write query documents over your traces, logs and metrics: fields, filters, aggregations, formulas and result shapes.

A query is one JSON document: which rows to read, how to combine them, over what time range, and what shape to return. The same language defines [monitor conditions](https://docs.struct.ai/observability/monitors/create.md).

## A first query

The 10 routes with the most 5xx responses in the last hour:

```json theme={null}
{
  "kind": "query",
  "range": { "last": "1h" },
  "result": "table",
  "queries": [
    {
      "name": "errors",
      "signal": "traces",
      "filter": "service.name = 'checkout-api' AND http.response.status_code >= 500",
      "aggregation": "count()",
      "groupBy": ["http.route"],
      "order": [{ "by": "errors", "direction": "desc" }],
      "limit": 10
    }
  ]
}
```

Run it with `struct telemetry query --file query.json --json` or the [`query_telemetry` MCP tool](https://docs.struct.ai/mcp/tools/telemetry). Struct checks each field and metric name the document uses against the telemetry your workspace sent in the last 7 days, and every error says how to fix the document. A name Struct can't check within 2 seconds is listed in `namesUnchecked` (`names_unchecked` from the MCP tool) with the reason, and the query runs anyway; the CLI names it on stderr. Before you read an empty result as no data, confirm those names with `struct telemetry describe`.

Find real names first. Do not guess them:

```bash theme={null}
struct telemetry describe traces --search route --json
struct telemetry describe metrics --search "queue age" --json
struct telemetry describe logs --field severity_text --json
```

`struct telemetry guide` prints a compact guide, and `struct telemetry guide top_n` prints a worked example.

## Document

| Key | Meaning |
| - | - |
| `kind` | `"query"`. |
| `queries` | The queries to run. Each has a `name` that formulas, `output` and `order` refer to. |
| `formulas` | Optional arithmetic over queries. |
| `range` | `{"last": "1h"}`, or `{"start": ..., "end": ...}` in ISO 8601. |
| `result` | The shape to return. See [Results](#results). |
| `output` | Which query or formula to return. By default, the last formula or the only query. |
| `version` | Optional. Defaults to the current language version, `struct-condition/1`. |

## Queries

| Key | Meaning |
| - | - |
| `signal` | `traces` (a row per span), `logs` (a row per log line) or `metrics`. |
| `filter` | Which rows to keep. See [Filters](#filters). Leave it out to match everything. |
| `aggregation` | Traces and logs: `count()`, `count_distinct(f)`, `sum(f)`, `avg(f)`, `min(f)`, `max(f)`, `p50(f)`, `p75(f)`, `p90(f)`, `p95(f)`, `p99(f)`, `rate()` (per second), `max(timestamp)`, `max_by(value, ordering_field)`. |
| `groupBy` | Up to 4 fields. One result per combination. |
| `having` | Drops groups by their aggregated value, such as `"count() >= 100"`. |
| `shift` | Reads the same range this long ago. `"1d"` compares with the same time yesterday. |
| `perEntity` | Aggregates per entity first, then across entities: `"perEntity": {"by": ["gen_ai.conversation.id"], "aggregation": "count()"}, "aggregation": "max()"`. |
| `select` | Raw results only: the fields to return. `"attributes"` is the whole attribute map. |
| `order` | `[{"by": "errors", "direction": "desc"}]`, by a field or an output name. |
| `limit` | At most 1000. |
| `cursor` | A result's `nextCursor`, to read the rows after it. See [Read the next page](#read-the-next-page). |
| `metric` | Metrics only. See [Metrics](#metrics). |

## Fields

| Signal | Standard fields |
| - | - |
| Traces | `service.name`, `span.name`, `kind` (`server`, `client`, `internal`, `producer`, `consumer`), `status` (`ok`, `error`, `unset`), `status.message`, `duration` (milliseconds), `trace_id`, `span_id`, `parent_span_id`, `timestamp` |
| Logs | `service.name`, `severity_text`, `severity_number` (17 and above is an error), `body`, `trace_id`, `span_id`, `timestamp` |
| Metrics | The metric's labels and `service.name` |

The instrumentation scope fields `scope.name` and `scope.version` are also standard for all three signals. Any other name is an attribute, so `http.route` reads the span attribute `http.route`. `attributes.<key>` is always an attribute and `resource.<key>` is always a resource attribute.

## Filters

| Form | Example |
| - | - |
| Comparison | `duration > 2000` |
| `LIKE`, `ILIKE` (`%` is the wildcard) | `span.name LIKE 'POST %'` |
| `REGEXP`, `CONTAINS` | `body CONTAINS 'timeout'` |
| `BETWEEN` | `duration BETWEEN 100 AND 500` |
| `IN` | `kind IN ('server', 'consumer')` |
| `EXISTS` | `http.route EXISTS` |
| `has`, `hasAny` | `hasAny(tags, ['a', 'b'])` |
| Another query's groups | `trace_id IN query('slow')` |

Negate a whole expression with `NOT (duration > 2000)` or `NOT hasAny(tags, ['a', 'b'])`; keyword operators also accept forms such as `kind NOT IN ('server', 'consumer')`. In logs, a bare quoted string searches the body: `'timeout'`. `NOT` binds tighter than `AND`, and `AND` tighter than `OR`, so write `a AND (b OR c)`.

## Metrics

```json theme={null}
{
  "kind": "query",
  "range": { "last": "1h" },
  "result": "table",
  "queries": [
    {
      "name": "backlog",
      "signal": "metrics",
      "metric": { "metric": "queue_depth", "time": "latest", "space": "max" },
      "groupBy": ["queue"]
    }
  ]
}
```

`time` reduces each series over the range, and `space` combines the series in each group. A metric's value is in its own unit. `struct telemetry describe metrics --field <name> --json` lists a metric's type and labels.

| Type | `time` | `space` |
| - | - | - |
| Gauge (a current value) | `latest`, `avg`, `min`, `max`, `sum`, `count` | `sum`, `avg`, `min`, `max`, `p50`, `p75`, `p90`, `p95`, `p99` |
| Counter (a running total) | `increase`, `rate` (per second; resets handled), `latest` (most recent sample) | `sum`, `avg`, `min`, `max`, `p50`, `p75`, `p90`, `p95`, `p99` |
| `updown_counter` (a total that can decrease) | `latest`, `avg`, `min`, `max`, `sum`, `count`, `increase`, `rate` | `sum`, `avg`, `min`, `max`, `p50`, `p75`, `p90`, `p95`, `p99` |
| Histogram | Leave it out | `p50`, `p75`, `p90`, `p95`, `p99` (pooled), `avg`, `max`, `min` |

Histogram `max` and `min` require delta temporality and recorded, non-negative minimum and maximum values. Otherwise, the query is refused; use a percentile or `avg` instead. Check temporality with `struct telemetry describe metrics --field <name> --json`.

## Formulas

Error rate per route, as a percentage:

```json theme={null}
{
  "kind": "query",
  "range": { "last": "15m" },
  "result": "table",
  "queries": [
    {
      "name": "A",
      "signal": "traces",
      "filter": "kind = 'server' AND status = 'error'",
      "aggregation": "count()",
      "groupBy": ["http.route"]
    },
    {
      "name": "B",
      "signal": "traces",
      "filter": "kind = 'server'",
      "aggregation": "count()",
      "groupBy": ["http.route"],
      "having": "count() >= 100"
    }
  ],
  "formulas": [{ "name": "F1", "expression": "A / B * 100", "unit": "%" }]
}
```

Formulas use `+ - * /`, parentheses, numbers, query and formula names, `abs()`, `min(x, y)`, `max(x, y)` and `now()`. `unit` is required and declares the result's unit; nothing is converted. Queries in a formula use the same `groupBy`, or none.

Where a query has no row for a group, `count()`, `count_distinct()` and `rate()` read 0. Anything else has no value, so the formula has no value there. Division by zero has no value.

## Results

| `result` | Returns | Needs |
| - | - | - |
| `scalar` | One number per group. | |
| `table` | Top N rows, using the query's `order` and `limit`. | |
| `time_series` | Points per group. | `step`, such as `"5m"` |
| `raw` | The rows' `select` fields, newest 100 by default. | |
| `trace` | One trace's spans, parents first. | `traceId` |
| `distribution` | A value distribution. | `field`, `buckets` |
| `fields` | Field names and their top values. | |

`raw`, `distribution` and `fields` require a `traces` or `logs` output query. A metrics output returns `ok: false` and CLI `query_invalid`; use `scalar`, `table` or `time_series` for metrics instead.

For `scalar`, `table` and `time_series`, `output` can list several names sharing a `groupBy`, to return them side by side:

```json theme={null}
{
  "kind": "query",
  "range": { "last": "6h" },
  "result": "time_series",
  "step": "5m",
  "output": ["requests", "errors", "p95_ms"],
  "queries": [
    {
      "name": "requests",
      "signal": "traces",
      "filter": "kind = 'server'",
      "aggregation": "count()",
      "groupBy": ["service.name"]
    },
    {
      "name": "errors",
      "signal": "traces",
      "filter": "kind = 'server' AND status = 'error'",
      "aggregation": "count()",
      "groupBy": ["service.name"]
    },
    {
      "name": "p95_ms",
      "signal": "traces",
      "filter": "kind = 'server'",
      "aggregation": "p95(duration)",
      "groupBy": ["service.name"]
    }
  ]
}
```

A response has `ok`, `errors`, `result` and `plan`, which says where each query read from. It returns at most 200 rows or points. When there are more, `truncated` is `true`, and `total_<key>` gives the count when Struct knows it.

## Read the next page

A `raw` or `table` result that was cut, by the query's `limit` or by the 200-row response, has `nextCursor`. Run the same document again with that value as `cursor` in one of its queries:

```json theme={null}
{
  "kind": "query",
  "range": { "last": "1h" },
  "result": "raw",
  "queries": [
    {
      "name": "errors",
      "signal": "logs",
      "filter": "severity_number >= 17",
      "select": ["timestamp", "body"],
      "limit": 200,
      "cursor": "eyJ2IjoxLCJkIjoi…"
    }
  ]
}
```

Repeat while a result has `nextCursor`. Each page starts after the last row the previous one returned, so no row is skipped or repeated. If a result has `truncated: true` without `nextCursor`, more rows matched but continuation is unavailable; narrow the filter or range to retrieve them.

* Change nothing but `cursor`. A cursor works only with the document that returned it; with another filter, order, limit or range the response is `ok: false` and says so.
* Every page reads the first page's time range. With `"range": {"last": "1h"}`, the hour ends when the first page ran, however much later the next page runs.
* A table computes its groups again for each page. One ordered by a value, such as a count, pages exactly while those values stay the same; if new data changes them between pages, a group near a page boundary can be skipped or repeated. Order by the group field, or use a range that has ended, when that matters.
* The cursor is opaque text. Don't build or edit one.

Only `raw` and `table` results have pages. For other results, narrow the range or add filters.

## Use one query's groups in another

`field IN query('Q')` keeps rows whose `field` is one of query `Q`'s group values. What the checkout service logged during its slow requests:

```json theme={null}
{
  "kind": "query",
  "range": { "last": "1h" },
  "result": "raw",
  "output": "logs",
  "queries": [
    {
      "name": "slow",
      "signal": "traces",
      "filter": "service.name = 'checkout-api' AND kind = 'server' AND duration > 2000",
      "groupBy": ["trace_id"]
    },
    {
      "name": "logs",
      "signal": "logs",
      "filter": "service.name = 'checkout-api' AND trace_id IN query('slow')",
      "select": ["timestamp", "trace_id", "severity_text", "body"]
    }
  ]
}
```

`Q` groups by exactly one field, of the same type as `field`, and uses no semijoin itself. `NOT IN query('Q')` keeps the rows outside `Q`'s groups.

## Read one record in full

Long field values in query results are cut short. To read a row in full, run a `raw` query with `"select": ["*"]`: every stored column, such as `SpanAttributes`, `Events.*` and `Links.*` for a span or `Body` and `LogAttributes` for a log, each value up to 100,000 characters. `"*"` stands alone in `select`.

```json theme={null}
{
  "kind": "query",
  "range": { "last": "1h" },
  "result": "raw",
  "queries": [
    {
      "name": "span",
      "signal": "traces",
      "filter": "trace_id = '4bf92f3577b34da6a3ce929d0e0e4736' AND span_id = '00f067aa0ba902b7'",
      "select": ["*"],
      "limit": 1
    }
  ]
}
```

A span's logs are a second query: the same filter with `"signal": "logs"`. To read one log row again, filter by the `id` a raw logs row returns: `"filter": "id = 'ROW_ID'"`. The CLI does both:

```bash theme={null}
struct telemetry span TRACE_ID SPAN_ID --json
struct telemetry log ROW_ID --json
```

`span` looks back 24 hours and `log` 1 hour by default; pass `--since` (at most 30 days) for an older span, and `--at TIMESTAMP` (the row's `timestamp`) for an older log row. A log lookup by `id` reads every log in its range, so keep that range narrow: a few hours, not days.

## What the language can't express

* Fields of logs and spans combined in one row. Run two queries, or use `IN query('Q')` to link them.
* Grouping by a computed value, such as a regular expression's capture. Match the known values with `REGEXP` or `CONTAINS` in separate queries.
* Funnels and sequences, and spans and logs in one timeline.
* Time windows anchored to a deploy. Use an absolute `range` with the deploy's time.
* Lookup tables, such as a customer's tier.

The telemetry query tools and CLI accept only query documents. When a question falls outside the language, split it into questions the language can answer, or report what you couldn't answer.

## Errors

| Outcome | CLI | Next step |
| - | - | - |
| `ok: false`: the document is invalid | Exit 1, `query_invalid` | Apply the fix in `errors`, then run it again. |
| `error`: the document is valid, the read failed | Exit 1, `telemetry_query_rejected` | Narrow the range, add filters, or read fewer rows. Then run it again. |
| HTTP 429: the workspace is past its [query limits](https://docs.struct.ai/observability/query.md#limits) | Exit 1, `telemetry_query_rate_limited` | Wait `retryAfterSeconds`, then run it again. |

## Value at the greatest ordering field

`max_by(value, ordering_field)` returns a numeric value from the row with the
greatest numeric ordering field or timestamp in each group and window. For example,
`max_by(duration, timestamp)` returns the latest span's duration, while
`max_by(severity_number, struct.observations.process_sequence)` follows report sequence.
Equal ordering values select the higher result. Missing or invalid numeric inputs
are skipped; no matching valid rows means no data. This reads raw records and uses
the existing query limits. Text results and forecasting over `max_by` are not supported.

Use `condition_guide` topics `observation_health` and `observation_health_reports`
for an Observation-health monitor and an inspection query. Health reports describe
configured Observations; they do not prove application telemetry is arriving.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.