Skip to main content

Query gzip JSON logs in S3 with Athena

Define an external table in Amazon Athena to query gzipped or plain NDJSON logs in S3. With partition projection, Athena can resolve date and hour folders from the table definition as new logs arrive.

The files​

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

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

Each line is one application log record with the same keys:

{"ts":"2026-11-19T08:14:03.512Z","level":"ERROR","service":"checkout","msg":"card declined","trace_id":"5b8efff798038103d269b633813fc60c","http":{"method":"POST","path":"/orders","status":502},"tags":["payments","retry"]}

The JSON SerDes need one record per line. A pretty-printed file, with one object spread over several lines, fails with HIVE_CURSOR_ERROR: Row is not a valid JSON Object.

Gzip needs no setting​

For CSV, TSV and JSON, Athena picks the compression from the file extension. A .gz object is read as gzip, and an object without an extension as plain text, so a table can mix both. Per Use compression in Athena:

  • The extension must be lowercase. .GZ is not recognized.
  • tar.gz archives and ZIP files are not supported.
  • Gzip files can't be split, so one worker reads each object from start to end. Section 3 of AWS's performance tuning tips covers file sizes.

Pick a JSON SerDe​

A SerDe maps each top-level JSON key to a column of the same name. Athena has two for JSON lines:

SerDeClassUse it when
Hive JSON SerDeorg.apache.hive.hcatalog.data.JsonSerDeThe default choice.
OpenX JSON SerDeorg.openx.data.jsonserde.JsonSerDeYou need its options: ignore.malformed.json, dots.in.keys, case.insensitive, or mapping.<column> for keys that are reserved words.

AWS documents that the OpenX JSON SerDe can return non-deterministic results: more or fewer rows than expected, or nulls where the data has values. Its workaround is the Hive JSON SerDe. Use OpenX only for one of its options.

Create the table with partition projection​

With partition projection, Athena computes the partition values from table properties when a query runs, instead of reading partitions registered in the AWS Glue Data Catalog. A new hour is queryable as soon as its first object lands.

CREATE DATABASE IF NOT EXISTS logs;

CREATE EXTERNAL TABLE logs.app (
ts string,
level string,
service string,
msg string,
trace_id string,
http struct<method:string, path:string, status:int>,
tags array<string>
)
PARTITIONED BY (`date` string, hour string)
ROW FORMAT SERDE 'org.apache.hive.hcatalog.data.JsonSerDe'
LOCATION 's3://<bucket>/<prefix>/'
TBLPROPERTIES (
'projection.enabled' = 'true',
'projection.date.type' = 'date',
'projection.date.format' = 'yyyy-MM-dd',
'projection.date.range' = '2026-11-01,NOW',
'projection.date.interval' = '1',
'projection.date.interval.unit' = 'DAYS',
'projection.hour.type' = 'integer',
'projection.hour.range' = '0,23',
'projection.hour.digits' = '2'
);

The supported types page lists every property. For this table:

  • projection.date.format is a Java DateTimeFormatter pattern, and the dates in projection.date.range must use it. Set the start to the day of your first file. NOW moves the end forward; NOW-90DAYS would limit the table to recent data.
  • Projected dates are generated in UTC. Your folders must be UTC too, or a day's filter reads the wrong hours.
  • projection.hour.digits of 2 produces 00 to 23, matching hour=08.
  • The folders use the column=value form, so Athena finds them under LOCATION with no storage.location.template. The next section shows the template for other layouts.
  • date is a reserved word in Athena DDL, so it is in backticks. SELECT statements can use it unquoted.
  • Nested objects are struct columns and arrays are array columns. Declare the fields you query, with their types.

Once projection is on, Athena ignores any partitions registered for the table in the Glue Data Catalog, and SHOW PARTITIONS lists none of the projected ones. A partition column without projection properties fails every query with HIVE_METASTORE_ERROR: ... missing projection configuration.

Folders without names​

Amazon Data Firehose, by default, writes yyyy/MM/dd/HH/ folders with no date= in the key. Project them as one date column with an hourly interval, and map it to the key with storage.location.template, as in AWS's Firehose example:

CREATE EXTERNAL TABLE logs.app_firehose (
ts string,
level string,
service string,
msg string
)
PARTITIONED BY (datehour string)
ROW FORMAT SERDE 'org.apache.hive.hcatalog.data.JsonSerDe'
LOCATION 's3://<bucket>/<prefix>/'
TBLPROPERTIES (
'projection.enabled' = 'true',
'projection.datehour.type' = 'date',
'projection.datehour.format' = 'yyyy/MM/dd/HH',
'projection.datehour.range' = '2026/11/01/00,NOW',
'projection.datehour.interval' = '1',
'projection.datehour.interval.unit' = 'HOURS',
'storage.location.template' = 's3://<bucket>/<prefix>/${datehour}/'
);

The template needs a ${column} placeholder for every partition column and must end with /. Filter with strings in the same format: WHERE datehour >= '2026/11/19/00'.

Filter and group​

Filter on the partition columns in every query. Athena reads only the folders those filters allow, and bills for the bytes it reads. A filter on a JSON field alone reads every object in the projected range.

Errors per service on one day:

SELECT service, count(*) AS errors
FROM logs.app
WHERE date = '2026-11-19'
AND level = 'ERROR'
GROUP BY service
ORDER BY errors DESC;

Struct fields use dot notation. Server errors per path over three days, with the latest one:

SELECT http.path,
count(*) AS responses,
max(from_iso8601_timestamp(ts)) AS last_seen
FROM logs.app
WHERE date BETWEEN '2026-11-17' AND '2026-11-19'
AND http.status >= 500
GROUP BY http.path
ORDER BY responses DESC;

The partition columns are strings, so date compares as text, which sorts correctly for yyyy-MM-dd. A query with only a lower bound reads up to today, because projection never generates dates after NOW:

SELECT date, hour, count(*) AS records
FROM logs.app
WHERE date >= '2026-11-19'
GROUP BY date, hour
ORDER BY date, hour;

UNNEST turns an array into rows. Records per tag:

SELECT tag, count(*) AS records
FROM logs.app
CROSS JOIN UNNEST(tags) AS t(tag)
WHERE date = '2026-11-19'
GROUP BY tag
ORDER BY records DESC;

To see which object a row came from, select the "$path" column:

SELECT "$path", msg
FROM logs.app
WHERE date = '2026-11-19' AND hour = '08' AND level = 'ERROR'
LIMIT 10;

Lines with different shapes​

A SerDe table fits when every line has the same keys. When one prefix mixes record shapes, or a nested object holds whatever the producer sent, declare one string column, read the whole line into it, and parse it in the query with JSON functions:

CREATE EXTERNAL TABLE logs.raw (
line string
)
PARTITIONED BY (`date` string, hour string)
STORED AS TEXTFILE
LOCATION 's3://<bucket>/<prefix>/'
TBLPROPERTIES (
'projection.enabled' = 'true',
'projection.date.type' = 'date',
'projection.date.format' = 'yyyy-MM-dd',
'projection.date.range' = '2026-11-01,NOW',
'projection.hour.type' = 'integer',
'projection.hour.range' = '0,23',
'projection.hour.digits' = '2'
);
SELECT json_extract_scalar(line, '$.service') AS service,
json_extract_scalar(line, '$.http.status') AS status,
count(*) AS records
FROM logs.raw
WHERE date = '2026-11-19'
GROUP BY 1, 2
ORDER BY records DESC;
  • With no ROW FORMAT, Athena splits each line on byte 0x01. JSON escapes control characters inside strings, so the whole line lands in line.
  • With single-day precision, interval and interval.unit default to one day, so this table leaves them out.
  • json_extract_scalar returns text, or NULL for an object or array. Cast numbers before arithmetic, and use json_extract to get an object or array as JSON.
  • A new field is queryable the moment it appears, with no ALTER TABLE.

Copy to Parquet​

Each query reads the full compressed size of every object in its partitions, whatever columns it selects. If you query the same days repeatedly, copy them to Parquet once with CTAS. Athena then reads only the columns a query uses:

CREATE TABLE logs.app_parquet
WITH (
format = 'PARQUET',
write_compression = 'SNAPPY',
external_location = 's3://<output_bucket>/app_parquet/',
partitioned_by = ARRAY['date']
) AS
SELECT from_iso8601_timestamp(ts) AS ts,
level, service, msg, trace_id,
http.path AS path,
http.status AS status,
date
FROM logs.app
WHERE date BETWEEN '2026-11-01' AND '2026-11-19';
  • Partition columns go last in the SELECT list.
  • external_location must be empty. Athena does not overwrite data and fails the query instead.
  • One CTAS or INSERT INTO query writes at most 100 partitions. Load longer ranges in batches with INSERT INTO.

Where Send2Bucket fits​

Send2Bucket is a hosted endpoint for JSON events and OpenTelemetry that writes them to your own bucket as gzip NDJSON under date and hour folders, so the tables above apply with one more partition column. 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. Project stream with the enum type and list your stream IDs.
  • date and hour are the UTC hour Send2Bucket received the records, which matches projection's UTC dates.
  • Every line is an envelope: signal is event, log, span or metric, and the record is in data. Events keep the keys you sent and OpenTelemetry records follow the OTLP JSON mapping, so data changes shape from line to line. Use the one-string-column table.

The Athena querying guide has the full table definition with projection on stream, date and hour, a view with typed columns, IAM permissions, S3 Tables, and queries for events, logs and spans. To send OpenTelemetry from your services in the first place, see OpenTelemetry to Amazon S3.

Notes​

  • Cost. Athena bills per terabyte scanned, rounded up to the nearest megabyte with a 10 MB minimum per query. See Athena pricing. S3 request charges for reading the objects are billed separately.
  • Zero rows, no error. Projection returns no rows, not an error, when a filter falls outside projection.*.range, or when the format or LOCATION doesn't match the keys in the bucket. Compare a key from aws s3 ls with the properties.
  • Empty partitions. Athena projects every day and hour in range, even where no object exists. AWS recommends classic Glue partitions when more than half of the projected partitions are empty.
  • Other engines. Projection works only in Athena. Amazon Redshift Spectrum and Amazon EMR read the table's partitions from the Glue Data Catalog, where projection registers none.