Skip to main content

Query OpenTelemetry traces and logs in S3 with SQL

The OpenTelemetry Collector’s S3 exporter writes OTLP/JSON by default. Use DuckDB to unpack those files into rows for individual spans, log records and metrics. You can then look up a trace by ID, find slow spans or aggregate a metric over time.

What OTLP/JSON looks like on disk​

The Collector's awss3 exporter uses the otlp_json marshaler unless you choose another one. With s3_prefix: otel and compression: gzip, our run wrote keys like these, one object per batch the exporter received:

otel/year=2026/month=11/day=23/hour=00/minute=29/traces_261535476.json.gz
otel/year=2026/month=11/day=23/hour=00/minute=29/logs_142300149.json.gz
otel/year=2026/month=11/day=23/hour=00/minute=29/metrics_112581768.json.gz

Each object holds one JSON document per line, shaped like an OTLP export request: spans nest under the resource that produced them, then under the instrumentation scope. One trace line, cut to a single span:

{"resourceSpans": [{
"resource": {"attributes": [{"key": "service.name", "value": {"stringValue": "payments"}}]},
"scopeSpans": [{
"scope": {"name": "telemetrygen"},
"spans": [{
"traceId": "ddf8e20f1f5aa3013cb41c832a5cd007",
"spanId": "ede556d6bde182a0",
"parentSpanId": "6e7e8ee6d836fd1e",
"name": "okey-dokey-0",
"kind": 2,
"startTimeUnixNano": "1795393797803698463",
"endTimeUnixNano": "1795393798053698463",
"attributes": [{"key": "peer.service", "value": {"stringValue": "telemetrygen-client"}}],
"status": {"code": 2}
}]
}],
"schemaUrl": "https://opentelemetry.io/schemas/1.4.0"
}]}

Logs and metrics follow the same three levels:

SignalTop levelPer scopeRecords
TracesresourceSpansscopeSpansspans
LogsresourceLogsscopeLogslogRecords
MetricsresourceMetricsscopeMetricsmetrics, each with a gauge, sum, histogram, exponentialHistogram or summary holding dataPoints

The OTLP JSON encoding sets the rules that matter for SQL:

  • Attributes are a list of {key, value} objects, not a JSON object keyed by name. The value is typed: stringValue, intValue, doubleValue, boolValue, arrayValue, kvlistValue or bytesValue (common.proto). Finding service.name means searching the list.
  • 64-bit integers are strings. That covers startTimeUnixNano, endTimeUnixNano, timeUnixNano and intValue. Cast them before doing arithmetic.
  • Enums are integers. Span kind 2 is server and 3 is client, and status.code 2 is error (trace.proto). Log severityNumber 17 to 20 is error (log data model).
  • Trace and span IDs are hex strings, and field names are lowerCamelCase.
  • Fields at their default value are often left out. A root span has no parentSpanId, and a span with an unset status has "status": {}.

The file exporter specification uses the same shape, one document per line, so the views below read those files too once you change the path.

Connect DuckDB to S3​

Install httpfs and create a secret. With AWS credentials on the machine:

INSTALL httpfs;
LOAD httpfs;
CREATE SECRET s3_read (TYPE s3, PROVIDER credential_chain, REGION '<region>');

For an access key or S3-compatible storage, pass KEY_ID, SECRET, ENDPOINT and URL_STYLE 'path' instead; see the DuckDB guide and DuckDB's S3 documentation. Reading needs s3:ListBucket and s3:GetObject.

Flatten the files into views​

Three views turn the nesting into one row per span, log record and metric. Each keeps the resource and scope the record came from, as JSON, so the queries can read resource attributes:

CREATE VIEW spans AS
SELECT year, month, day, rs.resource, ss.scope, span
FROM read_ndjson('s3://<bucket>/<prefix>/**/traces_*.json.gz',
hive_partitioning = true,
columns = {resourceSpans: 'STRUCT(resource JSON, scopeSpans STRUCT(scope JSON, spans JSON[])[])[]'}),
unnest(resourceSpans) AS r(rs),
unnest(rs.scopeSpans) AS s(ss),
unnest(ss.spans) AS x(span);

CREATE VIEW logs AS
SELECT year, month, day, rl.resource, sl.scope, log
FROM read_ndjson('s3://<bucket>/<prefix>/**/logs_*.json.gz',
hive_partitioning = true,
columns = {resourceLogs: 'STRUCT(resource JSON, scopeLogs STRUCT(scope JSON, logRecords JSON[])[])[]'}),
unnest(resourceLogs) AS r(rl),
unnest(rl.scopeLogs) AS s(sl),
unnest(sl.logRecords) AS x(log);

CREATE VIEW metrics AS
SELECT year, month, day, rm.resource, sm.scope, metric
FROM read_ndjson('s3://<bucket>/<prefix>/**/metrics_*.json.gz',
hive_partitioning = true,
columns = {resourceMetrics: 'STRUCT(resource JSON, scopeMetrics STRUCT(scope JSON, metrics JSON[])[])[]'}),
unnest(resourceMetrics) AS r(rm),
unnest(rm.scopeMetrics) AS s(sm),
unnest(sm.metrics) AS x(metric);
  • columns types only the levels the views walk through and leaves each record as JSON, so a new attribute or a metric type you did not expect never changes the schema. DuckDB does not infer anything.
  • Each unnest in FROM turns one list into rows and can refer to the one before it.
  • hive_partitioning turns the year=, month=, day=, hour= and minute= folders into columns (Hive partitioning). A filter such as WHERE year = 2026 AND month = 11 AND day = 23 skips the objects in other folders; those folders are when the Collector wrote the object, not the time inside the records.
  • The file name prefix (traces_, logs_, metrics_) keeps each view to one signal. If you set file_prefix or turn off compression, change the pattern to match.

Read attributes with a macro​

A macro searches any object's attributes list for a key and returns the value as text, whatever its type:

CREATE MACRO attr(obj, name) AS (
SELECT coalesce(a->>'$.value.stringValue', a->>'$.value.intValue',
a->>'$.value.doubleValue', a->>'$.value.boolValue')
FROM unnest(json_extract(obj, '$.attributes[*]')) AS t(a)
WHERE a->>'$.key' = name);

It works on resources, spans, log records and metric data points: attr(resource, 'service.name'), attr(span, 'peer.service'), attr(log, 'order.id'). Cast the result for numbers, for example attr(span, 'http.response.status_code')::INTEGER. Arrays and key-value lists come back as NULL; read those with json_extract (JSON functions).

Span durations and the slowest spans per service​

Cast the nanosecond strings to HUGEINT before subtracting; the result divided by 1e6 is milliseconds. The two slowest spans of each service:

SELECT attr(resource, 'service.name') AS service,
span->>'$.name' AS span,
((span->>'$.endTimeUnixNano')::HUGEINT
- (span->>'$.startTimeUnixNano')::HUGEINT) / 1e6 AS duration_ms,
span->>'$.traceId' AS trace_id
FROM spans
QUALIFY row_number() OVER (PARTITION BY service ORDER BY duration_ms DESC) <= 2
ORDER BY service, duration_ms DESC;
┌──────────┬──────────────┬─────────────┬──────────────────────────────────┐
│ service │ span │ duration_ms │ trace_id │
├──────────┼──────────────┼─────────────┼──────────────────────────────────┤
│ checkout │ okey-dokey-0 │ 0.123 │ d8b43e7a5f6ba0fa9d8c6894048d921f │
│ checkout │ lets-go │ 0.123 │ d8b43e7a5f6ba0fa9d8c6894048d921f │
│ payments │ okey-dokey-0 │ 250.0 │ 151881c37b9c480a2fdaf888c3aac5da │
│ payments │ lets-go │ 250.0 │ 151881c37b9c480a2fdaf888c3aac5da │
└──────────┴──────────────┴─────────────┴──────────────────────────────────┘

Error spans​

status.code 2 is an error. Unset status codes are often missing rather than 0, so test for the value you want:

SELECT attr(resource, 'service.name') AS service,
span->>'$.name' AS span,
span->>'$.traceId' AS trace_id,
span->>'$.status.message' AS message
FROM spans
WHERE (span->>'$.status.code')::INTEGER = 2
ORDER BY trace_id
LIMIT 4;

One trace by ID​

Every span of a trace, root first. make_timestamp_ns turns nanoseconds into a timestamp (timestamp functions), and lower makes the match work for IDs pasted in upper case:

SELECT make_timestamp_ns((span->>'$.startTimeUnixNano')::BIGINT) AS start_time,
span->>'$.spanId' AS span_id,
span->>'$.parentSpanId' AS parent_id,
span->>'$.name' AS span,
(span->>'$.kind')::INTEGER AS kind,
((span->>'$.endTimeUnixNano')::HUGEINT
- (span->>'$.startTimeUnixNano')::HUGEINT) / 1e6 AS duration_ms
FROM spans
WHERE lower(span->>'$.traceId') = lower('<trace_id>')
ORDER BY start_time, parent_id NULLS FIRST;
┌───────────────────────────────┬──────────────────┬──────────────────┬──────────────┬───────┬─────────────┐
│ start_time │ span_id │ parent_id │ span │ kind │ duration_ms │
├───────────────────────────────┼──────────────────┼──────────────────┼──────────────┼───────┼─────────────┤
│ 2026-11-23 00:29:57.803826724 │ 0620b5ed3a17a0e3 │ NULL │ lets-go │ 3 │ 250.0 │
│ 2026-11-23 00:29:57.803826724 │ 1042aec4a4cc739d │ 0620b5ed3a17a0e3 │ okey-dokey-0 │ 2 │ 250.0 │
└───────────────────────────────┴──────────────────┴──────────────────┴──────────────┴───────┴─────────────┘

Log records written inside a span carry its traceId too; query the logs view with the same filter to put them next to the spans.

Search logs by severity, body and attribute​

Log records by service and severity:

SELECT attr(resource, 'service.name') AS service,
log->>'$.severityText' AS severity,
count(*) AS logs
FROM logs
GROUP BY ALL
ORDER BY logs DESC;
┌──────────┬──────────┬───────┐
│ service │ severity │ logs │
├──────────┼──────────┼───────┤
│ checkout │ Info │ 20 │
│ payments │ Error │ 2 │
└──────────┴──────────┴───────┘

severityText is whatever the logger wrote; severityNumber is the normalized level. Errors and worse whose body mentions a decline, with an attribute alongside:

SELECT make_timestamp_ns((log->>'$.timeUnixNano')::BIGINT) AS time,
attr(resource, 'service.name') AS service,
log->>'$.body.stringValue' AS body,
attr(log, 'order.id') AS order_id
FROM logs
WHERE (log->>'$.severityNumber')::INTEGER >= 17
AND log->>'$.body.stringValue' ILIKE '%declined%'
ORDER BY time;
┌───────────────────────────────┬──────────┬───────────────┬───────────┐
│ time │ service │ body │ order_id │
├───────────────────────────────┼──────────┼───────────────┼───────────┤
│ 2026-11-23 00:29:58.320418799 │ payments │ card declined │ ord_20005 │
│ 2026-11-23 00:29:58.322698899 │ payments │ card declined │ ord_20005 │
└───────────────────────────────┴──────────┴───────────────┴───────────┘

The body is an AnyValue like an attribute value, so a structured body is under $.body.kvlistValue instead. Every log for one attribute value:

SELECT make_timestamp_ns((log->>'$.timeUnixNano')::BIGINT) AS time,
log->>'$.severityText' AS severity,
log->>'$.body.stringValue' AS body
FROM logs
WHERE attr(log, 'order.id') = 'ord_20005';

A metric series​

Gauge and sum metrics keep their points in dataPoints, each with timeUnixNano and either asDouble or asInt (a string):

SELECT attr(resource, 'service.name') AS service,
metric->>'$.name' AS metric,
make_timestamp_ns((p->>'$.timeUnixNano')::BIGINT) AS time,
coalesce((p->>'$.asDouble')::DOUBLE, (p->>'$.asInt')::BIGINT) AS value
FROM metrics,
unnest(json_extract(coalesce(metric->'$.gauge', metric->'$.sum'), '$.dataPoints[*]')) AS t(p)
WHERE metric->>'$.name' = 'gen'
ORDER BY time
LIMIT 5;
┌──────────┬─────────┬───────────────────────────────┬────────┐
│ service │ metric │ time │ value │
├──────────┼─────────┼───────────────────────────────┼────────┤
│ checkout │ gen │ 2026-11-23 00:29:58.563494506 │ 0.0 │
│ checkout │ gen │ 2026-11-23 00:29:58.56661417 │ 1.0 │
│ checkout │ gen │ 2026-11-23 00:29:58.567242146 │ 2.0 │
│ checkout │ gen │ 2026-11-23 00:29:58.567764365 │ 3.0 │
│ checkout │ gen │ 2026-11-23 00:29:58.569394114 │ 4.0 │
└──────────┴─────────┴───────────────────────────────┴────────┘

Data points have their own attributes, so attr(p, '<key>') splits a series by label. Histograms keep bucketCounts and explicitBounds instead of a single value.

Athena​

We have not tested Athena SQL against the Collector's nested files, so this page gives none. The Athena guide covers Send2Bucket's one-record-per-line objects: a table with partition projection, and the same search through the attribute list with CROSS JOIN UNNEST.

Where Send2Bucket fits​

Send2Bucket is a hosted OTLP endpoint that writes your telemetry to your own bucket, so there is no Collector or exporter to run (OpenTelemetry to Amazon S3). Per Delivery format, it has already done the flattening: each log record, span or metric is one NDJSON line, with resource and scope copied onto it and the record in data in the same OTLP JSON mapping. Four views give the same columns as above, so every query on this page runs unchanged:

CREATE VIEW records AS
SELECT *
FROM read_ndjson('s3://<bucket>/<prefix>/s2b/stream=*/date=*/hour=*/*.ndjson.gz',
hive_partitioning = true,
columns = {signal: 'VARCHAR', resource: 'JSON', scope: 'JSON', data: 'JSON'});

CREATE VIEW spans AS SELECT resource, scope, data AS span FROM records WHERE signal = 'span';
CREATE VIEW logs AS SELECT resource, scope, data AS log FROM records WHERE signal = 'log';
CREATE VIEW metrics AS SELECT resource, scope, data AS metric FROM records WHERE signal = 'metric';

On our sample dataset these return 40 spans of 0.123 ms each, 20 checkout / Info log records and 20 gauge points. Filter records on date and hour, the UTC hour Send2Bucket received the data. The DuckDB querying guide covers the other destinations, including Iceberg and DuckLake tables.

Notes​

  • Many small objects. Without batching in the Collector pipeline, the exporter writes one object per request it receives: our test wrote 44 objects for 88 records. Each object is a separate GET, so small objects make queries slow and add request charges.
  • Cost. Every query downloads and parses the gzip objects it matches. Filter on the folder columns, and copy days you query often to Parquet with COPY ... TO ... (FORMAT parquet).
  • Timestamps. BIGINT holds nanosecond timestamps until the year 2262, so make_timestamp_ns(...::BIGINT) is safe; HUGEINT for the subtraction rules out overflow altogether.
  • A view holds no data and reads the bucket each time. Keep the CREATE SECRET, views and macro in a .sql file and run it at the start of a session.