# Read NDJSON from S3 with Polars

Use [Polars](https://docs.pola.rs/) to read plain or gzipped NDJSON files from S3. Check the inferred schema before aggregating records, especially when a field only appears later in a file.

## The files

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

```text
s3://<bucket>/<prefix>/date=2026-11-23/hour=00/<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_00361pk2klrlp0eurim3mi7all8f0","stream_id":"3f6c2a9e-8b1d-4e7a-9c55-0d2b7e41a8f3","batch_id":"bat_00361pk2dn7r4395obrtf0h1kfmp0","received_at":"2026-11-23T00:16:47.243186Z","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 Polars to S3

Polars talks to S3 itself; it needs no `s3fs` or `boto3` for keys and environment credentials.

```bash
pip install polars
```

Every reader takes a `storage_options` dict. On a machine with `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY` set, or an instance or task role, name the region and let Polars find the rest:

```python
import polars as pl

storage_options = {"aws_region": "<region>"}
```

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

```python
storage_options = {
    "aws_endpoint_url": "<endpoint>",
    "aws_access_key_id": "<access_key_id>",
    "aws_secret_access_key": "<secret_access_key>",
    "aws_region": "<region>",
}
```

Leave out `aws_endpoint_url` for Amazon S3. Add `"aws_allow_http": "true"` for an endpoint on plain HTTP. For a named profile or an assumed role, pass `credential_provider=pl.CredentialProviderAWS(profile_name="<profile>")` instead, which [needs `boto3`](https://docs.pola.rs/api/python/stable/reference/api/polars.CredentialProviderAWS.html). Reading needs `s3:ListBucket` on the bucket and `s3:GetObject` on the objects; use a read-only key.

## Read one object, then a glob

[`pl.read_ndjson`](https://docs.pola.rs/api/python/stable/reference/api/polars.read_ndjson.html) reads into memory. Nested objects become `Struct` columns:

```python
df = pl.read_ndjson("s3://<bucket>/<object_key>", storage_options=storage_options)
df.select("received_at", "signal",
          event=pl.col("data").struct.field("event"),
          user_id=pl.col("data").struct.field("user_id")).head(3)
```

```text
┌─────────────────────────────┬────────┬────────────┬──────────┐
│ received_at                 ┆ signal ┆ event      ┆ user_id  │
│ ---                         ┆ ---    ┆ ---        ┆ ---      │
│ str                         ┆ str    ┆ str        ┆ str      │
╞═════════════════════════════╪════════╪════════════╪══════════╡
│ 2026-11-23T00:16:47.243186Z ┆ event  ┆ page.view  ┆ usr_0009 │
│ 2026-11-23T00:16:47.243186Z ┆ event  ┆ email.sent ┆ usr_0006 │
│ 2026-11-23T00:16:47.243186Z ┆ event  ┆ page.view  ┆ usr_0032 │
└─────────────────────────────┴────────┴────────────┴──────────┘
```

Gzip needs no option. The Polars reference for `read_ndjson` and `scan_ndjson` does not mention compression, but Polars 2.1.0 decompressed our gzip objects, and did so for a gzip object without a `.gz` name too, so it goes by the bytes, not the name. Check this on your version before you depend on it.

For many objects, use [`pl.scan_ndjson`](https://docs.pola.rs/api/python/stable/reference/api/polars.scan_ndjson.html) with a glob. It returns a LazyFrame: nothing is read until `.collect()`.

```python
SOURCE = "s3://<bucket>/<prefix>/date=*/hour=*/*.ndjson.gz"

pl.scan_ndjson(SOURCE, storage_options=storage_options).select(pl.len()).collect()
```

`**` matches any number of folders, as in `s3://<bucket>/<prefix>/**/*.ndjson.gz`.

## Pass a schema

Polars infers the columns from the first 100 lines (`infer_schema_length`) of the **first file** and applies that schema to every line of every file. Fields that do not appear there are dropped without an error. In the sample object the first 100 lines are JSON events, so the OpenTelemetry fields further down vanish:

```python
pl.scan_ndjson(SOURCE, storage_options=storage_options).collect_schema().names()
# ['v', 'delivery_batch_id', 'stream_id', 'batch_id', 'received_at', 'signal', 'data']
```

The `resource` and `scope` keys of the span lines are missing, and `pl.col("data").struct.field("name")` fails with `StructFieldNotFoundError`. `infer_schema_length=None` reads the whole first file, but in our test a field that first appeared in the second file was still dropped. The fix is to say what you want. Declare the fields you query, as [`schema`](https://docs.pola.rs/api/python/stable/reference/api/polars.scan_ndjson.html) takes them; keys you leave out are skipped:

```python
DATA = pl.Struct({
    "event": pl.String,
    "user_id": pl.String,
    "plan": pl.String,
    "path": pl.String,
    "order_id": pl.String,
    "cents": pl.Int64,
    "items": pl.List(pl.Struct({"sku": pl.String, "qty": pl.Int64})),
})
SCHEMA = {"received_at": pl.String, "signal": pl.String, "data": DATA}

events = pl.scan_ndjson(SOURCE, schema=SCHEMA, storage_options=storage_options)
```

A line without one of these fields gets a null, and a file that adds new fields next week changes nothing.

## Use the key prefixes as columns

Folders named `key=value` are Hive-style partitions. Polars [reads those for Parquet and IPC](https://docs.pola.rs/user-guide/io/hive/), and `scan_ndjson` has no `hive_partitioning` option in 2.1. Add the object path with `include_file_paths` and pull the values out of it:

```python
events = (
    pl.scan_ndjson(SOURCE, schema=SCHEMA, include_file_paths="file",
                   storage_options=storage_options)
    .with_columns(
        received_at=pl.col("received_at").str.to_datetime(time_zone="UTC"),
        date=pl.col("file").str.extract(r"/date=([^/]+)/").str.to_date(),
        hour=pl.col("file").str.extract(r"/hour=(\d+)/").cast(pl.Int8),
    )
)
```

A filter on these columns does not skip objects; every object the glob matches is downloaded and decompressed. To read less, narrow the glob itself:

```python
day = pl.scan_ndjson("s3://<bucket>/<prefix>/date=2026-11-23/hour=*/*.ndjson.gz",
                     schema=SCHEMA, storage_options=storage_options)
```

## Filter and group

A LazyFrame lets the optimizer [push filters and column selection down](https://docs.pola.rs/user-guide/lazy/optimizations/) to the scan. `d` is shorthand for the `data` column. Events by name, with revenue from `order.paid`:

```python
d = pl.col("data")

(events
 .filter(pl.col("signal") == "event", pl.col("date") >= pl.date(2026, 11, 1))
 .group_by(event=d.struct.field("event"))
 .agg(events=pl.len(), revenue_usd=d.struct.field("cents").sum() / 100)
 .sort("events", descending=True)
 .collect())
```

```text
┌────────────┬────────┬─────────────┐
│ event      ┆ events ┆ revenue_usd │
│ ---        ┆ ---    ┆ ---         │
│ str        ┆ u32    ┆ f64         │
╞════════════╪════════╪═════════════╡
│ page.view  ┆ 177    ┆ 0.0         │
│ order.paid ┆ 53     ┆ 4161.0      │
│ email.sent ┆ 47     ┆ 0.0         │
│ signup     ┆ 23     ┆ 0.0         │
└────────────┴────────┴─────────────┘
```

Polars sums missing values to `0`, where SQL engines return `NULL`. Users who viewed the pricing page, by plan:

```python
(events
 .filter(d.struct.field("event") == "page.view", d.struct.field("path") == "/pricing")
 .group_by(plan=d.struct.field("plan"))
 .agg(users=d.struct.field("user_id").n_unique())
 .sort("users", descending=True)
 .collect())
```

## Unnest structs and lists

[`unnest`](https://docs.pola.rs/api/python/stable/reference/lazyframe/api/polars.LazyFrame.unnest.html) turns a struct's fields into columns, and [`explode`](https://docs.pola.rs/api/python/stable/reference/lazyframe/api/polars.LazyFrame.explode.html) turns each list element into a row. Each `order.paid` event carries an `items` list:

```python
(events
 .filter(d.struct.field("event") == "order.paid")
 .unnest("data")
 .select("order_id", "cents", "items")
 .explode("items")
 .unnest("items")
 .sort("order_id")
 .head(3)
 .collect())
```

```text
┌───────────┬───────┬───────┬─────┐
│ order_id  ┆ cents ┆ sku   ┆ qty │
│ ---       ┆ ---   ┆ ---   ┆ --- │
│ str       ┆ i64   ┆ str   ┆ i64 │
╞═══════════╪═══════╪═══════╪═════╡
│ ord_20005 ┆ 19900 ┆ sku_1 ┆ 1   │
│ ord_20010 ┆ 2000  ┆ sku_1 ┆ 2   │
│ ord_20011 ┆ 19900 ┆ sku_1 ┆ 3   │
└───────────┴───────┴───────┴─────┘
```

`unnest("data")` fails with `DuplicateError` if a field inside `data` has the name of a top-level column (`data.path` and an `include_file_paths="path"` column, say). Rename one, or select the fields you need instead.

## Read lines as strings

When the files mix record shapes and you do not want one schema for all of them, read each line as text with [`pl.scan_lines`](https://docs.pola.rs/api/python/stable/reference/api/polars.scan_lines.html) (marked unstable in 2.1; it also decompressed gzip in our test). [`str.json_path_match`](https://docs.pola.rs/api/python/stable/reference/expressions/api/polars.Expr.str.json_path_match.html) pulls out one field as a string:

```python
lines = pl.scan_lines(SOURCE, storage_options=storage_options)

(lines
 .select(signal=pl.col("line").str.json_path_match("$.signal"))
 .group_by("signal")
 .agg(records=pl.len())
 .sort("records", descending=True)
 .collect())
```

Then decode one kind of line with its own schema using [`str.json_decode`](https://docs.pola.rs/api/python/stable/reference/expressions/api/polars.Expr.str.json_decode.html):

```python
spans = (
    lines
    .filter(pl.col("line").str.json_path_match("$.signal") == "span")
    .select(pl.col("line").str.json_decode(pl.Struct({
        "data": pl.Struct({"name": pl.String, "startTimeUnixNano": pl.String,
                           "endTimeUnixNano": pl.String}),
    })))
    .unnest("line")
    .unnest("data")
)
```

## Write Parquet

Gzip JSON has to be downloaded and parsed in full on every query. If you query the same days repeatedly, write the fields you use to Parquet once, one folder per day, with [`sink_parquet`](https://docs.pola.rs/api/python/stable/reference/api/polars.LazyFrame.sink_parquet.html) and [`pl.PartitionBy`](https://docs.pola.rs/api/python/stable/reference/api/polars.PartitionBy.html) (unstable in 2.1):

```python
(events
 .filter(pl.col("signal") == "event")
 .select("received_at", "date",
         event=d.struct.field("event"),
         user_id=d.struct.field("user_id"),
         cents=d.struct.field("cents"))
 .sink_parquet(pl.PartitionBy("s3://<output_bucket>/events_parquet/", key="date"),
               storage_options=storage_options))
```

This wrote `events_parquet/date=2026-11-23/00000000.parquet`. Read it back with [`scan_parquet`](https://docs.pola.rs/api/python/stable/reference/api/polars.scan_parquet.html), where Hive partitions work and a filter on `date` skips folders:

```python
(pl.scan_parquet("s3://<output_bucket>/events_parquet/", hive_partitioning=True,
                 storage_options=storage_options)
 .group_by("event")
 .agg(events=pl.len(), revenue_usd=pl.col("cents").sum() / 100)
 .sort("events", descending=True)
 .collect())
```

Writing needs `s3:PutObject` on the output bucket.

## 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`. Extract `stream` from the path as you did `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.
- One object can hold events, logs, spans and metrics, which is the schema trap above: pass a schema.
- `date` and `hour` are the UTC hour the records arrived, not the time inside them.

```python
(pl.scan_ndjson("s3://<bucket>/<prefix>/s2b/stream=*/date=*/hour=*/*.ndjson.gz",
                schema={"signal": pl.String}, storage_options=storage_options)
 .group_by("signal")
 .agg(records=pl.len())
 .sort("records", descending=True)
 .collect())
```

The [Python querying guide](../querying/python.md) has a full envelope schema with the OpenTelemetry fields, setup for Cloud Storage, R2 and Iceberg destinations, and queries for logs and spans. To send data in the first place, start with [Quick start](../quick-start.md).

## Notes

- `ComputeError: failed to retrieve first file schema ... expanded paths were empty` means the glob matched nothing. An `OSError` with `403 Forbidden` means the key, secret or bucket policy is wrong.
- Each query downloads every object the glob matches. Your storage provider bills the requests, and most bill egress too, so narrow the glob and run Polars in the bucket's region when you scan a lot.
- To query the same files with SQL instead, [DuckDB](../querying/duckdb.md) reads them with `read_ndjson` and Hive partitioning.
