SQLite 3.9 JSON1: querying sensor documents with type checks
Read sensor JSON without losing type information, then add a matching expression index and check how the query plan uses it.
Archive retrospective · Topic year 2015
In this article
The document boundary on a small data collector
A cold-storage yard keeps measurements in a local SQLite database. One sensor sends the temperature as a number and another sends that number as text. Some messages explicitly say null while others omit the field. The collector needs to retain the original message and let operators query by sensor and hour. SQLite 3.9.0, dated October 2015, introduced both the optional JSON1 extension and indexes on expressions. This retrospective uses four synthetic readings to exercise their combination. We can establish exactly which result is correct before looking at an index plan. Check the SQLite library the application actually loads. Availability of an extension in a current command-line tool says little about a device build of that period.
Valid JSON can contain unusable measurements
The table check validates JSON syntax. It can accept documents that omit a required field or use a different root shape. The application must define sensor identity, units, and supported message schema. Timestamp stays in a separate column. Our fixtures have fixed-width UTC text, so their chronological order agrees with text comparison. Do not generalize that property to arbitrary offsets and formats. Define how to handle future timestamps, late readings, and repeat delivery. The sample keeps the original valid document and rejects malformed JSON from the main table. Operations staff may need a separate quarantine for failures. Reprocessing can then retain the original sample time without letting an invalid document affect the regular hourly aggregate.
CREATE TABLE reading (
id INTEGER PRIMARY KEY,
sampled_at TEXT NOT NULL,
payload TEXT NOT NULL CHECK (json_valid(payload))
);
INSERT INTO reading (sampled_at, payload) VALUES
('2015-11-08T08:00:00Z', '{"sensor":"A","temperature":18.5}'),
('2015-11-08T08:05:00Z', '{"sensor":"A","temperature":"18.5"}'),
('2015-11-08T08:10:00Z', '{"sensor":"A","temperature":null}'),
('2015-11-08T08:15:00Z', '{"sensor":"B"}');
Work out which of the four values is valid
For the four records, json_type yields real, text, null, and SQL NULL for the missing path. Extracting just a single value can turn both explicit JSON null and the missing field into SQL NULL. The report accepts temperature only when its JSON type is integer or real. Sensor A has one qualifying numeric value, 18.5. Keep counts of text, explicit null, and missing fields separate if they reflect different device problems. The sample missing field belongs to sensor B. Test that its presence does not change A's numbers. Flag a supplier whose version starts emitting strings. Blind numeric coercion can treat a malformed measurement as zero and hide the firmware issue behind a plausible average.
Index the expression that the report actually uses
Operators start with a sensor and select a time interval. The index uses the sensor extraction expression and then the timestamp. SQLite's expression index matches how the query writes the expression; an altered expression need not use it. Keep the sensor path stable in the report and inspect its actual plan. Temperature validation remains a separate predicate. The engine may first locate the sensor and time interval, then check the candidate payloads. Four rows may be too few to demonstrate a planner choice. Populate test data with sensors that send at different rates and try narrow and broad ranges. Compare the read strategy. Do not make automated checks depend on the exact spelling of EXPLAIN QUERY PLAN output.
CREATE INDEX reading_sensor_at
ON reading (json_extract(payload, '$.sensor'), sampled_at);
EXPLAIN QUERY PLAN
SELECT sampled_at,
json_extract(payload, '$.temperature') AS value
FROM reading
WHERE json_extract(payload, '$.sensor') = 'A'
AND sampled_at >= '2015-11-08T08:00:00Z'
AND sampled_at < '2015-11-08T09:00:00Z'
AND json_type(payload, '$.temperature') IN ('integer', 'real')
ORDER BY sampled_at;
Measure the price paid on writes
Each new reading computes the indexed expression and updates the index. That is additional work for the write path. Make two lab copies with the same data and index only one of them. Run the report on both with small and large ranges. Then append the same number of readings in equal transaction batches. Record database size, ingestion time, and late report responses independently. Note SQLite version, storage hardware, and competing traffic. Measurements from an idle test process do not promise the same performance during a busy collection window. If the frequent field later becomes a normal column, decide how the ingestion transaction will keep that column and the original payload consistent.
Check availability and failure behavior together
Check sqlite_version() and run a small json_valid call against the application connection. If JSON1 is missing, give the report process a diagnostic before it begins reading measurements. Keep later JSON operators, JSONB, and generated columns outside this SQLite 3.9 exercise. Assert the expected accepted count, raw records, and exact numeric result for the fixture. Add malformed JSON, an unrecognized sensor, a reading on the hour boundary, and a duplicate packet. A half-open interval assigns the 09:00 sample to the next hour. Repeat the query after restarting the application. The lasting benefit is preserving the flexible message while meeting an explicit reporting contract. Fast retrieval does not make the underlying measurements trustworthy by itself.
Reader discussion
Which alternative architecture would you try for the same problem?
No comments yet. Be the first to contribute.
Write a comment