# Connect DuckDB to S3 and query JSON files

Use [DuckDB](../querying/duckdb.md) to query newline-delimited JSON (NDJSON) files in S3, including gzip files. Filter the object path to the dates you need, aggregate the rows with SQL and save the results as Parquet.

## The files

The examples read gzip NDJSON objects under date and hour prefixes:

```text
s3://<bucket>/<prefix>/date=2026-11-19/hour=08/<file>.ndjson.gz
```

Each line is one JSON object. These come from Send2Bucket's sample dataset, so each event sits inside a small envelope; your own lines will have other fields:

```json
{"v":1,"delivery_batch_id":"dlv_00361ph3ha13ummf535glgajq8b1s","stream_id":"3f6c2a9e-8b1d-4e7a-9c55-0d2b7e41a8f3","batch_id":"bat_00361ph3aqk2686au6sq08gq21ah8","received_at":"2026-11-22T23:50:11.890211Z","signal":"event","data":{"event":"order.paid","user_id":"usr_0003","plan":"team","ts":"2026-11-19T13:05:00Z","order_id":"ord_20005","cents":19900,"currency":"usd","items":[{"sku":"sku_1","qty":1}]}}
```

## Connect DuckDB to S3

Install the `httpfs` extension and create a secret. On a machine with AWS credentials (a profile, environment variables or an instance role), let DuckDB find them:

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

With an access key, or for S3-compatible storage such as Cloudflare R2 or MinIO, pass the key and the endpoint:

```sql
INSTALL httpfs;
LOAD httpfs;
CREATE SECRET s3_read (
  TYPE s3, KEY_ID '<access_key_id>', SECRET '<secret_access_key>', REGION '<region>',
  ENDPOINT '<endpoint>', URL_STYLE 'path');
```

Leave out `ENDPOINT` and `URL_STYLE` for Amazon S3. Add `USE_SSL false` for an endpoint on plain HTTP. Reading needs `s3:ListBucket` on the bucket and `s3:GetObject` on the objects; use a read-only key.

## Read the files with a glob

Check what a pattern matches before you read it. `**` matches any number of folders:

```sql
SELECT *
FROM glob('s3://<bucket>/<prefix>/**/*.ndjson.gz');
```

Then read one object. DuckDB picks gzip from the `.gz` extension and infers a column per top-level key:

```sql
SELECT received_at, signal, data.event, data.user_id
FROM read_json('s3://<bucket>/<object_key>')
LIMIT 3;
```

```text
┌───────────────────────────────┬─────────┬────────────┬──────────┐
│          received_at          │ signal  │   event    │ user_id  │
├───────────────────────────────┼─────────┼────────────┼──────────┤
│ 2026-11-22 23:50:11.890211+00 │ event   │ page.view  │ usr_0009 │
│ 2026-11-22 23:50:11.890211+00 │ event   │ email.sent │ usr_0006 │
│ 2026-11-22 23:50:11.890211+00 │ event   │ page.view  │ usr_0032 │
└───────────────────────────────┴─────────┴────────────┴──────────┘
```

Nested objects become `STRUCT` columns, so `data.event` works. To read every object, put the glob in the path. `read_ndjson` is `read_json` with the format fixed to one object per line:

```sql
SELECT count(*) AS records
FROM read_ndjson('s3://<bucket>/<prefix>/date=*/hour=*/*.ndjson.gz');
```

## Use the key prefixes as columns

Folders named `key=value` are Hive-style partitions. With `hive_partitioning`, DuckDB adds a column for each (`date` and `hour` here) and skips objects whose folder fails a filter on them:

```sql
SELECT date, hour, count(*) AS records
FROM read_ndjson('s3://<bucket>/<prefix>/date=*/hour=*/*.ndjson.gz',
                 hive_partitioning = true)
WHERE date >= DATE '2026-11-01'
GROUP BY ALL
ORDER BY ALL;
```

`date` comes back as a `DATE` and `hour` as a `BIGINT`. A filter on `date` or `hour` decides which objects are downloaded; a filter on a field inside the JSON still reads every object the glob matches. On a large bucket, always filter on the folders first.

## Pin the schema

DuckDB infers types from a sample of the lines. When the files mix record shapes, or a field first appears in next week's files, the inferred `STRUCT` changes and queries that worked can fail. List the columns you need and read nested parts as `JSON`:

```sql
CREATE VIEW events AS
SELECT *
FROM read_ndjson('s3://<bucket>/<prefix>/date=*/hour=*/*.ndjson.gz',
                 hive_partitioning = true,
                 columns = {received_at: 'TIMESTAMPTZ', signal: 'VARCHAR', data: 'JSON'});
```

Keys not listed are ignored. The view reads the bucket each time you query it; it holds no data.

## Filter and group

`->>` extracts a field from a `JSON` value as text; cast it for arithmetic. Events by name, with revenue from `order.paid`:

```sql
SELECT data->>'event' AS event,
       count(*) AS events,
       sum((data->>'cents')::INTEGER) / 100 AS revenue_usd
FROM events
WHERE signal = 'event'
  AND date >= DATE '2026-11-01'
GROUP BY ALL
ORDER BY events DESC;
```

```text
┌────────────┬────────┬─────────────┐
│   event    │ events │ revenue_usd │
├────────────┼────────┼─────────────┤
│ page.view  │    177 │        NULL │
│ order.paid │     53 │      4161.0 │
│ email.sent │     47 │        NULL │
│ signup     │     23 │        NULL │
└────────────┴────────┴─────────────┘
```

Users who viewed the pricing page, by plan:

```sql
SELECT data->>'plan' AS plan,
       count(DISTINCT data->>'user_id') AS users
FROM events
WHERE data->>'event' = 'page.view'
  AND data->>'path' = '/pricing'
GROUP BY ALL
ORDER BY users DESC;
```

## Unnest nested arrays

Each `order.paid` event carries an `items` array. `json_extract` with `[*]` returns the elements as a list, and `unnest` turns the list into rows:

```sql
SELECT data->>'order_id' AS order_id,
       item->>'sku' AS sku,
       (item->>'qty')::INTEGER AS qty
FROM events,
     unnest(json_extract(data, '$.items[*]')) AS t(item)
WHERE data->>'event' = 'order.paid'
ORDER BY order_id
LIMIT 3;
```

```text
┌───────────┬─────────┬───────┐
│ order_id  │   sku   │  qty  │
├───────────┼─────────┼───────┤
│ ord_20005 │ sku_1   │     1 │
│ ord_20010 │ sku_1   │     2 │
│ ord_20011 │ sku_1   │     3 │
└───────────┴─────────┴───────┘
```

When you want typed columns, `json_transform` converts the JSON to a `STRUCT` with the shape you give it, and fields come out already cast:

```sql
SELECT o.order_id, o.cents, i.sku, i.qty
FROM (
  SELECT json_transform(data, '{"order_id": "VARCHAR", "cents": "INTEGER",
                                "items": [{"sku": "VARCHAR", "qty": "INTEGER"}]}') AS o
  FROM events
  WHERE data->>'event' = 'order.paid'
), unnest(o.items) AS u(i)
ORDER BY o.order_id
LIMIT 3;
```

## Export to Parquet

Gzip JSON has to be downloaded and parsed in full on every query. If you query the same days repeatedly, copy the fields you use to Parquet once, partitioned by day:

```sql
COPY (
  SELECT received_at,
         data->>'event' AS event,
         data->>'user_id' AS user_id,
         (data->>'cents')::INTEGER AS cents,
         date
  FROM events
  WHERE signal = 'event'
) TO 's3://<output_bucket>/events_parquet' (FORMAT parquet, PARTITION_BY (date));
```

This writes one folder per day, `events_parquet/date=2026-11-22/`. Read it back the same way:

```sql
SELECT event, count(*) AS events, sum(cents) / 100 AS revenue_usd
FROM read_parquet('s3://<output_bucket>/events_parquet/*/*.parquet', hive_partitioning = true)
GROUP BY ALL
ORDER BY events DESC;
```

The `COPY` needs a secret with `s3:PutObject` on the output bucket. Running it again fails while the folder holds files; add `OVERWRITE_OR_IGNORE` to the options to write over files with the same names.

## Where Send2Bucket fits

Send2Bucket is a hosted endpoint for JSON events and OpenTelemetry that writes them to your own bucket in exactly this layout, so everything above applies unchanged. Per [Delivery format](../delivery-format.md):

- Each delivery batch is one gzip NDJSON object at `<prefix>/s2b/stream=<stream_id>/date=YYYY-MM-DD/hour=HH/<delivery_batch_id>.ndjson.gz`.
- Read them all with `s3://<bucket>/<prefix>/s2b/stream=*/date=*/hour=*/*.ndjson.gz`. Hive partitioning adds `stream`, `date` and `hour`.
- The JSON you sent is in `data`, unchanged. `signal` is `event`, `log`, `span` or `metric`, and `received_at` is when Send2Bucket accepted the request.
- `date` and `hour` are the UTC hour the records arrived, not the time inside them. To select by event time, filter on your own timestamp and widen the `date` range to catch late arrivals.
- A retried write puts identical bytes under the same key, so retries never add objects. A client that resends a request does store its records twice; see [Delivery semantics](../delivery-semantics.md).

```sql
SELECT signal, count(*) AS records
FROM read_ndjson('s3://<bucket>/<prefix>/s2b/stream=*/date=*/hour=*/*.ndjson.gz')
GROUP BY ALL
ORDER BY records DESC;
```

The [DuckDB querying guide](../querying/duckdb.md) has the full column list for the envelope, setup for Cloud Storage, R2, Iceberg and DuckLake destinations, and queries for logs, spans and metrics. To send data in the first place, start with [Quick start](../quick-start.md).

## Notes

- A secret lasts for the session. `CREATE PERSISTENT SECRET` stores it, unencrypted, under `~/.duckdb/stored_secrets`, and loads it in later sessions.
- `No files found that match the pattern` means the glob matched nothing: run the `glob()` query above with the same path to see what it does match.
- Each query downloads every object it reads. Your storage provider bills the requests, and most bill egress too, so filter on `date` and `hour`, and run DuckDB in the bucket's region when you scan a lot.
