Create a BigQuery external table over JSON in Cloud Storage
Create an external table in BigQuery to query gzip NDJSON files in Cloud Storage. Define columns explicitly or use schema autodetection. If the files use Hive-style paths, expose their partition keys as columns so queries can skip unrelated files.
The files
The examples read gzip NDJSON objects under date and hour prefixes:
gs://<bucket>/events/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:
{"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}]}}
Before you start
- The dataset that holds the external table must be in the bucket's location: a bucket in
us-central1needs a dataset inus-central1or theUSmulti-region. See location considerations. - Creating the table needs
bigquery.tables.create(BigQuery Data Editor has it). Querying it needs read on the table andstorage.objects.getandstorage.objects.liston the bucket. A BigLake table moves the bucket permission to a connection, so users need access to the table only.
CREATE SCHEMA IF NOT EXISTS json_demo OPTIONS (location = '<location>');
Create the table with autodetect
Leave out the column list and BigQuery detects the schema. WITH PARTITION COLUMNS without a list detects the key=value folders as partition columns:
CREATE OR REPLACE EXTERNAL TABLE json_demo.events_auto
WITH PARTITION COLUMNS
OPTIONS (
format = 'NEWLINE_DELIMITED_JSON',
compression = 'GZIP',
uris = ['gs://<bucket>/events/*'],
hive_partition_uri_prefix = 'gs://<bucket>/events'
);
compression = 'GZIP'is required for.gzfiles. Without it, BigQuery treats the files as uncompressed. The setting applies to every file the table reads, so keep uncompressed files under another prefix.- Each URI can hold one
*, after the bucket name.gs://<bucket>/events/*.ndjson.gzalso works and skips other files. hive_partition_uri_prefixis the part of the path before the firstkey=valuefolder, without the wildcard.
Check what it found:
bq show --schema --format=prettyjson <project>:json_demo.events_auto
Autodetect picks a random file and reads up to its first 500 lines (schema auto-detection). Nested objects become RECORD columns and arrays become REPEATED ones, and strings that look like numbers, booleans or dates are converted. A field that appears only in other files is missing from the schema, and every file the URI matches must share a compatible schema. Autodetect is fine for a first look at uniform files; for a table people depend on, declare the schema.
Declare the schema
List the columns you need, and type the partition columns in the order they appear in the path:
CREATE OR REPLACE EXTERNAL TABLE json_demo.events (
received_at TIMESTAMP,
signal STRING,
data STRUCT<
event STRING,
user_id STRING,
plan STRING,
path STRING,
order_id STRING,
cents INT64,
items ARRAY<STRUCT<sku STRING, qty INT64>>
>
)
WITH PARTITION COLUMNS (date DATE, hour INT64)
OPTIONS (
format = 'NEWLINE_DELIMITED_JSON',
compression = 'GZIP',
uris = ['gs://<bucket>/events/*'],
hive_partition_uri_prefix = 'gs://<bucket>/events',
ignore_unknown_values = true,
require_hive_partition_filter = true
);
ignore_unknown_values = trueskips keys that are not in the schema, such asdelivery_batch_idanddata.currencyhere. Without it, a line with an extra key is an error.require_hive_partition_filter = truerejects any query without a filter ondateorhour, so nobody scans the whole bucket by accident.received_atparses as aTIMESTAMPbecause it is RFC 3339 with aZ. See JSON data types for the accepted formats.- Partition column names cannot match a column in the files. The partition key cannot be changed after the table is created; recreate the table instead.
The table holds no data. Each query lists the matching folders and reads their files.
Query nested fields
STRUCT fields take dot notation. Events by name, with revenue from order.paid, for one month:
SELECT data.event AS event,
COUNT(*) AS events,
SUM(data.cents) / 100 AS revenue_usd
FROM json_demo.events
WHERE date BETWEEN DATE '2026-11-01' AND DATE '2026-11-30'
AND signal = 'event'
GROUP BY event
ORDER BY events DESC;
The filter on date decides which folders are read. A filter on a field inside the JSON, such as signal, still reads every file in those folders.
UNNEST turns the items array into one row per element:
SELECT data.order_id, item.sku, item.qty
FROM json_demo.events, UNNEST(data.items) AS item
WHERE date >= DATE '2026-11-01'
AND data.event = 'order.paid'
ORDER BY data.order_id
LIMIT 3;
To find which file a row came from, select the _FILE_NAME pseudocolumn. It needs an alias:
SELECT _FILE_NAME AS file, COUNT(*) AS records
FROM json_demo.events
WHERE date = DATE '2026-11-19'
GROUP BY file
ORDER BY file;
Keep changing fields as JSON
A STRUCT schema fits fields that keep their shape. When the files mix record shapes, or new keys keep arriving, keep the variable part as BigQuery's JSON type and pick fields at query time. Google documents JSON columns for load jobs into native tables; its external table pages do not say an NDJSON external table accepts one. The approach that works with documented options is to read each line as one string with the CSV reader, then parse it:
CREATE OR REPLACE EXTERNAL TABLE json_demo.event_lines (line STRING)
WITH PARTITION COLUMNS (date DATE, hour INT64)
OPTIONS (
format = 'CSV',
field_delimiter = '\x01',
quote = '',
compression = 'GZIP',
uris = ['gs://<bucket>/events/*'],
hive_partition_uri_prefix = 'gs://<bucket>/events'
);
Quoting is off, and the delimiter is byte 0x01, which valid JSON never holds unescaped, so each line arrives whole. PARSE_JSON turns it into a JSON value. Field access (doc.data.event) returns JSON; JSON_VALUE returns a string you can group on, and LAX_INT64 a number you can add:
SELECT JSON_VALUE(doc.data.event) AS event,
COUNT(*) AS events,
SUM(LAX_INT64(doc.data.cents)) / 100 AS revenue_usd
FROM (
SELECT SAFE.PARSE_JSON(line) AS doc
FROM json_demo.event_lines
WHERE date >= DATE '2026-11-01'
)
WHERE JSON_VALUE(doc.signal) = 'event'
GROUP BY event
ORDER BY events DESC;
JSON_QUERY_ARRAY turns a JSON array into an ARRAY<JSON> for UNNEST:
SELECT JSON_VALUE(doc.data.order_id) AS order_id,
JSON_VALUE(item.sku) AS sku,
LAX_INT64(item.qty) AS qty
FROM (
SELECT SAFE.PARSE_JSON(line) AS doc
FROM json_demo.event_lines
WHERE date >= DATE '2026-11-01'
), UNNEST(JSON_QUERY_ARRAY(doc.data.items)) AS item
WHERE JSON_VALUE(doc.data.event) = 'order.paid';
JSON values cannot be compared, so GROUP BY and WHERE need JSON_VALUE or a conversion function around them. A path that does not exist returns NULL, not an error, so check spelling when a column comes back empty.
Copy to a native table
An external table reads and parses the files on every query. Google's JSON limitations note that BigQuery cannot read a gzip file in parallel and that one gzip file can be at most 4 GB. If you query the same days repeatedly, copy them once into a native table, partitioned and clustered:
CREATE TABLE json_demo.events_native
PARTITION BY DATE(received_at)
CLUSTER BY signal
AS
SELECT received_at, signal, data
FROM json_demo.events
WHERE date BETWEEN DATE '2026-11-01' AND DATE '2026-11-30';
Run it again for a new month with INSERT INTO json_demo.events_native SELECT .... Copying the same days twice stores them twice, so keep track of what you copied.
Where Send2Bucket fits
Send2Bucket is a hosted endpoint for JSON events and OpenTelemetry that writes them to your own Cloud Storage bucket as gzip NDJSON, so everything above applies. Per Delivery format:
- Each delivery batch is one object at
<prefix>/s2b/stream=<stream_id>/date=YYYY-MM-DD/hour=HH/<delivery_batch_id>.ndjson.gz. That is three partition keys:WITH PARTITION COLUMNS (stream STRING, date DATE, hour INT64), withhive_partition_uri_prefix = 'gs://<bucket>/<prefix>/s2b'. - Use
uris = ['gs://<bucket>/<prefix>/s2b/stream=*']. It keeps the destination's test objects unders2b/_verify/out of the table. - The JSON you sent is in
data, unchanged.signalisevent,log,spanormetric, and OpenTelemetry lines addresourceandscope. Logs, spans and metrics have different shapes, so oneSTRUCTschema does not fit them all; the line-as-string table above does. dateandhourare the UTC hour the records arrived, not the time inside them. To select by event time, filter on your own timestamp and widen thedaterange to catch late arrivals.
The BigQuery querying guide has the s2b.raw_lines external table and s2b.records view built this way, a scheduled LOAD DATA into a native table, and queries for logs, spans and metrics. OpenTelemetry to Google Cloud Storage covers granting Send2Bucket's service account access to the bucket and pointing exporters at it.
Notes
- With on-demand pricing, BigQuery bills the bytes each query reads from Cloud Storage. A dry run of a query on an external table can report 0 bytes even when the query reads data (external table limitations). Filter on the partition columns.
- External tables are read-only and cannot be clustered. BigQuery does not guarantee consistent results when files change while a query runs.
- Clean up with
DROP SCHEMA json_demo CASCADE;. Dropping an external table leaves the files in the bucket.