# Query JSON in S3 from Postgres with pg_duckdb

Install [pg_duckdb](https://github.com/duckdb/pg_duckdb) in [PostgreSQL](../querying/postgres.md) to query newline-delimited JSON in S3. From `psql`, use DuckDB’s `read_json` to read plain or gzipped files, join their rows to a Postgres table or save a local copy.

## When to use pg_duckdb

Use it when you run your own PostgreSQL, can install extensions, and want JSON from a bucket next to your tables: for a join, a report, or a periodic copy into a table your application reads. Managed services that do not offer the extension, such as Supabase, cannot use it; the [PostgreSQL guide](../querying/postgres.md#options) lists the other ways in. For ad hoc analysis outside Postgres, [DuckDB](../querying/duckdb.md) on its own reads the same files with less setup.

## 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}]}}
```

## Install pg_duckdb

The quickest start is the project's Docker image, tagged `<postgres major>-v<pg_duckdb version>`:

```bash
docker run -d --name pgduckdb -e POSTGRES_PASSWORD=<password> pgduckdb/pgduckdb:18-v1.2.1
docker exec -it pgduckdb psql -U postgres
```

The image loads pg_duckdb at startup and creates the extension in the `postgres` database. On your own server, build or install it as in the [compilation guide](https://github.com/duckdb/pg_duckdb/blob/v1.2.1/docs/compilation.md), add `shared_preload_libraries = 'pg_duckdb'` to `postgresql.conf`, restart, and run this in each database that needs it:

```sql
CREATE EXTENSION pg_duckdb;
```

Check both versions:

```sql
SELECT extversion FROM pg_extension WHERE extname = 'pg_duckdb';
SELECT * FROM duckdb.query('SELECT version() AS duckdb_version');
```

By default only superusers can run DuckDB queries. Anyone else gets `DuckDB execution is not allowed because you have not been granted the duckdb.postgres_role`, even through a view. Set [`duckdb.postgres_role`](https://github.com/duckdb/pg_duckdb/blob/v1.2.1/docs/settings.md#duckdbpostgres_role) to a role and grant it to the users who need it; the setting needs a restart.

## Add an S3 secret

[`duckdb.create_simple_secret`](https://github.com/duckdb/pg_duckdb/blob/v1.2.1/docs/secrets.md) stores an access key:

```sql
SELECT duckdb.create_simple_secret(
  type := 'S3', key_id := '<access_key_id>', secret := '<secret_access_key>', region := '<region>');
```

For S3-compatible storage such as Cloudflare R2 or MinIO, add the endpoint and path-style URLs, and `use_ssl := 'false'` for an endpoint on plain HTTP:

```sql
SELECT duckdb.create_simple_secret(
  type := 'S3', key_id := '<access_key_id>', secret := '<secret_access_key>', region := '<region>',
  endpoint := '<endpoint>', url_style := 'path');
```

To use the server's AWS credentials (environment variables, a profile or an instance role) instead of a key, create a server with the credential chain:

```sql
CREATE SERVER s3_chain TYPE 's3' FOREIGN DATA WRAPPER duckdb
OPTIONS (PROVIDER 'credential_chain', REGION '<region>');
```

- Secrets are stored in Postgres as a foreign server on the `duckdb` wrapper, with the key in a user mapping. They survive restarts, and pg_duckdb loads them into every DuckDB instance it starts.
- Each `create_simple_secret` call adds a server (`simple_s3_secret`, `simple_s3_secret_1`, ...). List them with `SELECT srvname, srvoptions FROM pg_foreign_server` and remove one with `DROP SERVER simple_s3_secret_1 CASCADE`.
- The credential chain runs in the Postgres server process, so it sees that process's environment and role, not your client's. It uses DuckDB's `aws` extension, which pg_duckdb [installs on first use](https://github.com/duckdb/pg_duckdb/blob/v1.2.1/docs/extensions.md#installing-extensions) from `extensions.duckdb.org`, so the server needs to reach that host once.
- Reading needs `s3:ListBucket` on the bucket and `s3:GetObject` on the objects; use a read-only key. pg_duckdb [redacts statements](https://github.com/duckdb/pg_duckdb/blob/v1.2.1/docs/secrets.md#secrets-in-logs-and-query-statistics) that contain `secret` or `key_id` from the server log, on a best-effort basis.

## Read the files with `read_json`

[`read_json`](https://github.com/duckdb/pg_duckdb/blob/v1.2.1/docs/functions.md#read_json) returns rows of type `duckdb.row`. Give the call an alias such as `r` and pick columns with `r['column']`; nested objects are DuckDB structs, so `r['data']['event']` reaches into one. gzip is detected from the `.gz` extension:

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

```text
          received_at          | signal |   event    | user_id
-------------------------------+--------+------------+----------
 2026-11-23 00:16:47.243186+00 | event  | page.view  | usr_0009
 2026-11-23 00:16:47.243186+00 | event  | email.sent | usr_0006
 2026-11-23 00:16:47.243186+00 | event  | page.view  | usr_0032
```

Put a glob in the path to read every object, and fixed folder names to read fewer. `glob()` is not a Postgres function, so check what a pattern matches through [`duckdb.query`](https://github.com/duckdb/pg_duckdb/blob/v1.2.1/docs/functions.md#query), which runs a query in DuckDB's own SQL:

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

## Filter and group

`WHERE`, `GROUP BY` and aggregates work on `r[...]` expressions without casts. Events by name, with revenue from `order.paid`, for November's folders:

```sql
SELECT r['data']['event'] AS event,
       count(*) AS events,
       sum(r['data']['cents']) / 100 AS revenue_usd
FROM read_json('s3://<bucket>/<prefix>/date=2026-11-*/hour=*/*.ndjson.gz') r
WHERE r['signal'] = 'event'
GROUP BY r['data']['event']
ORDER BY events DESC;
```

```text
   event    | events | revenue_usd
------------+--------+-------------
 page.view  |    177 |
 order.paid |     53 |        4161
 email.sent |     47 |
 signup     |     23 |
```

The glob decides which objects are downloaded. A filter on a field inside the JSON still reads every object the glob matches.

## Pin the schema with `duckdb.query`

DuckDB infers a struct type for `data` from a sample of the lines. When files mix record shapes, the struct is the union of every field it saw, and a field that first appears next week changes it. In DuckDB you would pass `columns` and read `data` as `JSON`, but pg_duckdb's `read_json` [does not accept `columns`](https://github.com/duckdb/pg_duckdb/blob/v1.2.1/docs/functions.md#read_json), and in 1.2.1 it does not accept `hive_partitioning` either. Pass the whole DuckDB query to `duckdb.query` instead, and wrap it in a view with Postgres types:

```sql
CREATE VIEW s3_events AS
SELECT r['received_at']::timestamptz AS received_at,
       r['signal']::text AS signal,
       r['data']::json AS data
FROM duckdb.query($$
  SELECT * FROM read_ndjson('s3://<bucket>/<prefix>/date=*/hour=*/*.ndjson.gz',
    columns = {received_at: 'TIMESTAMPTZ', signal: 'VARCHAR', data: 'JSON'})
$$) r;
```

`data` is now each line's object as sent. Postgres `->>` works on it, and DuckDB runs the query:

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

```text
 plan | users
------+-------
 free |    13
 team |    13
 pro  |    12
```

The view holds no data; every query reads the bucket again. Casting the inferred struct with `r['data']::json` also works, but it writes out every field DuckDB saw across all lines, mostly as `null`, and rewrites timestamps.

## Copy the results into a Postgres table

Gzip JSON is downloaded and parsed in full on every query. For results you read often, keep a copy in Postgres. A materialized view is an ordinary heap table that `REFRESH` rebuilds from the bucket:

```sql
CREATE MATERIALIZED VIEW daily_orders AS
SELECT date_trunc('day', (data->>'ts')::timestamptz) AS day,
       count(*) AS orders,
       sum((data->>'cents')::int) AS cents
FROM s3_events
WHERE signal = 'event' AND data->>'event' = 'order.paid'
GROUP BY 1;

REFRESH MATERIALIZED VIEW daily_orders;
```

Index it, grant it to roles without `duckdb.postgres_role`, and use any Postgres function on it; none of that works on the bucket directly. `CREATE TABLE ... AS` with the same query makes a one-time copy.

When you `INSERT ... SELECT` from `read_json` or `duckdb.query`, [cast every `r[...]` column](https://github.com/duckdb/pg_duckdb/blob/v1.2.1/docs/types.md#casts-are-required-when-inserting-into-a-table) in the select list, or Postgres reports `expression is of type duckdb.unresolved_type`. Cast JSON to `json`, not `jsonb`: DuckDB runs the cast and has no `jsonb` type. Postgres converts `json` on the way into a `jsonb` column.

## 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`.
- The JSON you sent is in `data`, unchanged. `signal` is `event`, `log`, `span` or `metric`, and `resource` and `scope` hold the OpenTelemetry context.
- `date` and `hour` are the UTC hour the records arrived, not the time inside them.

The [PostgreSQL guide](../querying/postgres.md#create-the-tables) loads records into an `s2b_records` table and tracks loaded batches by `delivery_batch_id` in `s2b_loaded_batches`. With pg_duckdb, the load is one `psql` script, with no machine outside the database:

```sql
BEGIN;

CREATE TEMP TABLE new_lines ON COMMIT DROP AS
SELECT r['delivery_batch_id']::text  AS delivery_batch_id,
       r['batch_id']::text           AS batch_id,
       r['received_at']::timestamptz AS received_at,
       r['signal']::text             AS signal,
       r['resource']::json           AS resource,
       r['scope']::json              AS scope,
       r['data']::json               AS data
FROM duckdb.query($$
  SELECT *
  FROM read_ndjson('s3://<bucket>/<prefix>/s2b/stream=*/date=*/hour=*/*.ndjson.gz',
    hive_partitioning = true,
    columns = {delivery_batch_id: 'VARCHAR', batch_id: 'VARCHAR', received_at: 'TIMESTAMPTZ',
               signal: 'VARCHAR', resource: 'JSON', scope: 'JSON', data: 'JSON'})
  WHERE date >= current_date - 2
$$) r;

WITH new_batches AS (
  INSERT INTO s2b_loaded_batches (delivery_batch_id)
  SELECT DISTINCT delivery_batch_id FROM new_lines
  ON CONFLICT DO NOTHING
  RETURNING delivery_batch_id
)
INSERT INTO s2b_records
  (delivery_batch_id, batch_id, received_at, signal, resource, scope, data)
SELECT delivery_batch_id, batch_id, received_at, signal, resource, scope, data
FROM new_lines
JOIN new_batches USING (delivery_batch_id);

COMMIT;
```

- `hive_partitioning` adds `date`, and the filter on it inside the DuckDB query lists only the last few days of folders. Remove it for the first load, and after an outage, as the PostgreSQL guide explains.
- Run it with `psql -f` from cron. It cannot go in a function: pg_duckdb refuses DuckDB queries inside functions unless `duckdb.unsafe_allow_execution_inside_functions` is on.
- A second run loads nothing: on the sample data, the first run inserted 380 records and the second 0.

The PostgreSQL guide has the [example queries](../querying/postgres.md#example-queries) for the loaded table, and [DuckDB](../querying/duckdb.md) covers the same reads outside Postgres. To send data in the first place, start with [Quick start](../quick-start.md).

## Notes

- Each connection that runs a DuckDB query starts its own DuckDB instance, which may use up to [`duckdb.max_memory`](https://github.com/duckdb/pg_duckdb/blob/v1.2.1/docs/settings.md#duckdbmax_memory--duckdbmemory_limit) (4096 MB by default) and all CPU cores. Lower it, and `duckdb.threads`, when many connections query buckets.
- Postgres `json` and `jsonb` functions do not run inside DuckDB queries: on `s3_events`, `data::jsonb @> ...` and `jsonb_path_query_first` fail. Use [DuckDB's JSON functions](https://duckdb.org/docs/stable/data/json/json_functions), or run them on a copied table.
- If the first DuckDB query in a connection fails, pg_duckdb 1.2.1 did not load the secrets for the rest of that connection: later reads went to Amazon S3 without credentials. Reconnect; `CALL duckdb.recycle_ddb()` did not help.
- In a subquery or CTE, alias each `r[...]` column (`r['signal'] AS signal`), or the column comes out named `r`. See [Syntax guide and gotchas](https://github.com/duckdb/pg_duckdb/blob/v1.2.1/docs/gotchas_and_syntax.md).
- Each query downloads every object it reads. Your storage provider bills the requests, and most bill egress too, so narrow the glob and run Postgres in the bucket's region when you scan a lot.
