JSONB or typed classes: what the PostgreSQL planner sees

redb

Franck Pachot recently took apart a simple case on dev.to (JSONB performance: declare access patterns to PostgreSQL query planner). A table holds 100,000 measurements, each in a JSONB column. The query counts the measurements where three values are zero and groups them by lab. ANALYZE collects statistics for the JSONB column as a whole, not for the keys inside the document. For a condition like (record->>'value_1')::INT = 0, with no index and no statistics on that expression, the planner has nothing to go on: it takes the default equality selectivity, 0.5%, for each of the three conditions and multiplies them. 100,000 × 0.005³ is a hundredth of a row, so the estimate becomes one row. In fact about 12,500 rows match, and the plan comes out wrong. The cure is to declare the access pattern: expression indexes, a compound expression index or extended statistics.

We ran his example on our server and asked redb the same question, where the data has C# classes and every field has a type. Below are the plans, the row estimates and the times. The result first: on this query JSONB with a hand-made index is faster than redb. What typing buys for that is further down.

His case on our server

The table measurements(tick BIGSERIAL, record JSONB), 100,000 rows, with value_1, value_2, value_3 (0 or 1) and scientist_id in the document. A lookup table scientist_labs with 10,000 scientists and three lab names. The query:

SELECT s.lab_name, COUNT(*)
FROM measurements m
JOIN scientist_labs s ON s.scientist_id = (m.record->>'scientist_id')::BIGINT
WHERE (m.record->>'value_1')::INT = 0
  AND (m.record->>'value_2')::INT = 0
  AND (m.record->>'value_3')::INT = 0
GROUP BY s.lab_name
ORDER BY s.lab_name

PostgreSQL 18.6, jit = off. The time is a plain run of the statement, the median of three warm runs (why not EXPLAIN ANALYZE is explained at the end):

Variant Estimated / actual rows Join ms
no index 1 / 12,491 Nested Loop 29.7
three expression indexes 12,589 / 12,491 Hash Join 25.9
compound index on the three expressions 12,481 / 12,491 Hash Join 11.1
extended statistics only 7,263 × 2 / 6,245 × 2 Hash Join 26.5

The one-row estimate reproduces. The best variant, as in his article, is the compound index: 11.1 ms.

The same data in redb

In redb, data is described by a class. Pachot's document is closest to a class with a nested class: the values and the lab details live in the measurement itself.

public class LabInfo { public string LabName { get; set; } = ""; }

[RedbScheme("pachot_measurement_nested")]
public class NestedMeasurementProps
{
    public int Value1 { get; set; }
    public int Value2 { get; set; }
    public int Value3 { get; set; }
    public LabInfo? Lab { get; set; }
}

One difference from his schema is worth naming at once. His document holds scientist_id, and the lab name comes from the lookup table. Here the lab name lives in the measurement as a field of the nested class, so the query needs no lookup. The distributions are the same: the values 0 and 1 are equally likely and independent, the lab is picked uniformly out of 10,000, the name by (i % 3) + 1. The data is seeded with a fixed seed.

The question is the same, and it is one query:

var groups = await redb.Query<NestedMeasurementProps>()
    .Where(m => m.Value1 == 0 && m.Value2 == 0 && m.Value3 == 0)
    .GroupBy(m => m.Lab!.LabName)
    .SelectAsync(g => new { g.Key, Count = Agg.Count(g) });

The compiler checks the field names and their types. Value1 is an int here and is compared with an int. There is no ::INT cast in the query, because in the database it is a number, not text inside a document.

What the planner sees

redb Pro turns this query into one SQL statement:

SELECT COALESCE(json_agg(row_to_json(t))::text, '[]') FROM (SELECT
  pvt."Lab.LabName" AS "LabName",
  COUNT(*) AS "Count"
FROM (
  SELECT o_src._id AS _id_object, f0._string AS "Lab.LabName", o_src._dv AS "Value1", f2._long AS "Value2", f3._long AS "Value3"
  FROM (SELECT dv._id_object AS _id, dv._long AS _dv FROM _values dv WHERE (dv._id_structure = '1000016' AND dv._long = '0') AND dv._array_index IS NULL AND dv._id_object NOT IN (SELECT t._id FROM _objects t WHERE t._id_scheme = -10)) o_src
  LEFT JOIN _values f0 ON f0._id_object = o_src._id AND f0._id_structure = '1000020' AND f0._array_index IS NULL
  LEFT JOIN _values f2 ON f2._id_object = o_src._id AND f2._id_structure = '1000017' AND f2._array_index IS NULL
  LEFT JOIN _values f3 ON f3._id_object = o_src._id AND f3._id_structure = '1000018' AND f3._array_index IS NULL
) pvt
WHERE ((pvt."Value1" = '0' AND pvt."Value2" = '0') AND pvt."Value3" = '0')
GROUP BY pvt."Lab.LabName"
) t

The outer json_agg is the transport of the grouped result: the three group rows go to .NET as one JSON. The query itself is inside.

Each field is stored as a row of the values table: _id_structure says which field it is, and the value sits in the column of its type. Integers go to _long, strings to _string. To the planner, the condition Value1 = 0 is _id_structure = X AND _long = 0, a plain comparison of two columns that have statistics. There are no expressions to declare.

We created no index for this query. The system index IX__values__structure_long_object does the work, one index for every int field of every class in the database. Add another int field to the class tomorrow and filter on it, and the index is already there.

The source of the query is built from the first condition: the o_src subquery reads only the Value1 = 0 rows, about 50,000, not all 100,000 objects. The other conditions and the lab name are joined to that set, and GROUP BY gets only the 12,459 matching objects.

The plan: a parallel Hash Join of two index-only scans for Value1 = 0 and Value2 = 0, then an index-only lookup of Value3 = 0 per row, then a lookup of the lab name per match, a sort and a grouping.

Where the estimates go wrong

redb has its own statistics weakness, and the same plan shows it:

Node Estimated Actual
Value1 = 0 rows about 18,000 49,969
after Value2 864 per worker 24,863
after Value3 101 per worker 12,459
groups 3 3

The planner estimates one field reasonably well. But three fields of one object are three rows of the values table, and when it joins them by _id_object the planner treats them as independent. Each further condition multiplies the error, and by the end the estimate is 51 times below the actual count. Extended statistics cannot help here: they work on columns of one row, and these fields sit in different rows.

This time the error cost little: the low estimate chose an index lookup per row, and each such lookup is one index probe.

The figures

Variant Steps ms
JSONB, no index 1 29.7
JSONB, compound expression index 1 11.1
redb Pro, nested class, one GroupBy 1 50.5
redb Pro, tree, grouping by parent 2 67.6

Every redb variant returns the same answer, and it matches a count over the seeded data in .NET: California Scientific 4192, Industrial Labs 4179, Western Science People 4088.

The tree row is the same task in another model: the lab is the parent, its measurements are child objects. The first step groups the matching measurements by parent in one statement (GroupByRedb(m => m.ParentId), 49.6 ms); the second reads the lab names in two statements (17.5 ms). With a few small service statements, the server total is 67.6 ms.

On Pachot's question, a JSONB document with an index made by hand for this query is two to five times faster than redb: 11.1 and 29.7 ms against 50.5. Through the redb API, with the result parsed in .NET, it is 53.5 ms.

What types and foreign keys buy for that price

Pachot writes that with JSONB you declare the access paths to the planner yourself: which expressions, which index, which statistics. That is work done for every query that has to be fast, and redone when the query changes.

In redb, data has a type and relations from the start:

  • a field is declared in a C# class, and a query on it is checked by the compiler instead of failing on a typo in the string 'value_1';
  • an int is stored as a number, with no cast from text in every condition;
  • the indexes on the values tables are the same for every class; a new query does not add any;
  • a new field in a class needs neither a table migration nor a new index;
  • relations are held by foreign keys. Every value is tied to its object and to the definition of its field; the parent in a tree is a foreign key to an object, and so is a reference field to another object (RedbObject<T>). In Pachot's document, scientist_id is just a number inside JSON: the database will not check that such a scientist exists, and will not stop you from deleting a scientist the measurements refer to.

The price in our measurement: 50 ms where JSONB with a hand-made index answers in 11. If there is one hot query, the compound expression index wins. If there are many queries and they change along with the code, typing spares you a declaration for each of them.

How we measured

  • PostgreSQL 18.6 in a container, AMD Ryzen 5 5500U, jit = off, work_mem = 64MB, shared_buffers = 4GB, random_page_cost = 1.1. A separate database; nothing else ran on the server meanwhile.
  • redb Pro from the development branch, query planner on, default configuration.
  • Each figure is the median of three warm runs after one warm-up run.
  • Times are from plain runs. This server's kernel reads time through hpet (tsc is not offered), and one clock read costs 1.2 µs. EXPLAIN (ANALYZE) reads the clock for every row at every node, which here inflates the time 5 to 19 times. So the tables show the plain execution time of the statement, while the plans and row estimates come from EXPLAIN (ANALYZE, BUFFERS). For comparison, with timing on, the compound index showed 102 ms and the redb nested class 280 ms. For the same reason our figures cannot be compared with those in his article, only with each other.
  • The JSONB data was seeded with random(), as in his article, and gave 12,491 matching rows. The redb data was seeded from new Random(20261124) and gave 12,459.

Franck, if you read this: we would like your view on how the planner handles fields that live in different rows of one table, and what could be done better there.

Code and documentation: github.com/redbase-app/redb, articles: redbase.app/articles.

If this was useful, a ⭐ on GitHub helps others find it.