Postgres JSONB indexes: jsonb_ops vs jsonb_path_ops vs expression indexes, and the queries each one ignores
Which index to create for a JSONB column in PostgreSQL: the default GIN operator class, jsonb_path_ops, or a B-tree expression index. Measured on 1 million rows on Postgres 17.11: query times, index sizes and insert cost, why WHERE payload->>'key' = ... never uses a GIN index, why ? ignores jsonb_path_ops, and the partial-index statistics trap.
On this page
You put the flexible part of your data in a jsonb column, added CREATE INDEX ... USING gin (payload), and the query still does a sequential scan. That's not a planner bug. A Postgres index serves a set of operators applied to one exact expression, and the most common way to filter JSON, payload->>'user_id' = '4714', is not one of the operators a GIN index on payload can answer. This post loads 1 million JSON events into PostgreSQL 17.11, the major version Relyt One runs, and runs the same seven queries against four setups: no index, a GIN index with the default jsonb_ops, a GIN index with jsonb_path_ops, and B-tree expression indexes. You get the timings, index sizes and insert cost, a table that maps each WHERE clause to the index it can use, and two traps we hit along the way. If you only need the basics, our glossary has short entries for JSONB and GIN indexes.
Pick the index from the way your queries are written, not from the column:
- Containment,
payload @> '{"k": v}': a GIN index, either operator class. - jsonpath equality,
payload @@ '$.k == v'or@?with==: a GIN index, either operator class. - Key exists,
payload ? 'k': a GIN index with the defaultjsonb_opsclass only. - Text equality,
payload->>'k' = 'v': a B-tree index on(payload->>'k'). - Ranges and sorting,
(payload->>'k')::numeric > 10: a B-tree index on that exact cast.
The rest of the post shows where each of those rules comes from.
One table, one jsonb column, 1 million rows that look like product analytics events. Every row has a type, a user_id (one of 50,000), a device object and a two-element tags array. About 4% of rows are purchases with an amount, and about 1% carry a coupon:
CREATE TABLE events (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
payload jsonb NOT NULL
);
SELECT setseed(0.42);
INSERT INTO events (payload)
SELECT jsonb_strip_nulls(jsonb_build_object(
'type', CASE WHEN r < 0.60 THEN 'page_view'
WHEN r < 0.85 THEN 'click'
WHEN r < 0.95 THEN 'search'
WHEN r < 0.99 THEN 'purchase'
ELSE 'signup' END,
'user_id', (random() * 49999)::int + 1,
'amount', CASE WHEN r >= 0.95 AND r < 0.99 THEN round((random() * 500)::numeric, 2) END,
'coupon', CASE WHEN random() < 0.01 THEN 'BLACKFRIDAY' END,
'device', jsonb_build_object('os', (ARRAY['ios','android','web'])[1 + (g % 3)]),
'tags', to_jsonb(ARRAY['t' || (g % 50), 't' || ((g * 7) % 50)])
))
FROM (SELECT g, random() AS r FROM generate_series(1, 1000000) AS g) s;
VACUUM ANALYZE events;A typical row:
{"tags": ["t1", "t7"], "type": "click", "device": {"os": "android"}, "user_id": 18124}The table is 154 MB. We ran everything in a postgres:17.11-alpine container with default settings on an Apple M1 Pro laptop (5 CPUs given to Docker). Each number below is the median of seven runs after one warm-up run, with the table already cached in memory (by the operating system; it is larger than the default 128 MB shared_buffers), so read them as relative costs on one machine, not as a benchmark of your production server.
These are the seven queries:
-- 1. one user, containment
SELECT count(*) FROM events WHERE payload @> '{"user_id": 4714}';
-- 2. the same user, the way most application code writes it
SELECT count(*) FROM events WHERE payload->>'user_id' = '4714';
-- 3. one event type (1% of rows)
SELECT count(*) FROM events WHERE payload @> '{"type": "signup"}';
-- 4. rows that have a coupon key at all
SELECT count(*) FROM events WHERE payload ? 'coupon';
-- 5. rows with a specific coupon
SELECT count(*) FROM events WHERE payload @> '{"coupon": "BLACKFRIDAY"}';
-- 6. one user, jsonpath
SELECT count(*) FROM events WHERE payload @@ '$.user_id == 4714';
-- 7. a range on a number inside the document
SELECT count(*) FROM events WHERE (payload->>'amount')::numeric > 499;Median time in milliseconds for each query (columns) under each index setup (rows):
setup q1:@> q2:->> q3:type q4:? q5:coupon q6:@@ q7:range
no index 53.68 53.63 50.31 32.04 49.07 63.32 34.11
jsonb_ops 0.33 54.64 9.75 4.75 5.54 0.25 37.19
jsonb_path_ops 0.04 55.36 5.58 33.77 7.27 0.05 35.88
B-tree on exprs 54.75 0.03 53.58 33.26 47.01 65.78 0.06And what each index cost, built on the same 1 million rows:
- GIN jsonb_ops — Size (MB): 19; Build (s): 3.1
- GIN jsonb_path_ops — Size (MB): 16; Build (s): 0.9
- B-tree on user_id — Size (MB): 7.8; Build (s): 0.6
Four things stand out. Neither GIN index did anything for queries 2 and 7. jsonb_path_ops was several times faster than the default on the selective lookups (queries 1 and 6), somewhat faster on query 3, and level with it on query 5, where the winner changed from run to run. But it ignored query 4 completely. The B-tree expression indexes were the fastest of all, but only for the two queries written exactly like their expressions. And no index made query 3 as fast as query 1, because finding 10,000 rows is a different job from finding 15.
An index in Postgres doesn't index "a column". It indexes one expression, and it can only answer the operators of its operator class when they're applied to exactly that expression. The PostgreSQL documentation lists them: the default jsonb_ops class supports ?, ?|, ?&, @>, @? and @@; jsonb_path_ops supports @>, @? and @@.
payload->>'user_id' = '4714' is a text = applied to the expression payload->>'user_id'. The GIN index is on payload, and = on text isn't one of its operators, so the planner has nothing to match:
EXPLAIN (COSTS OFF) SELECT count(*) FROM events WHERE payload->>'user_id' = '4714';
Finalize Aggregate
-> Gather
Workers Planned: 2
-> Partial Aggregate
-> Parallel Seq Scan on events
Filter: ((payload ->> 'user_id'::text) = '4714'::text)You have two fixes. Rewrite the filter as containment, which the GIN index understands:
SELECT count(*) FROM events WHERE payload @> '{"user_id": 4714}';Or keep the query and give it an index on the expression it uses:
CREATE INDEX events_user_id ON events ((payload->>'user_id'));If you rewrite, check the JSON types first; containment is stricter than ->> (see trap 1 below). Rewriting is usually right when you already have a GIN index and filter on many different keys. The expression index is right when one or two keys carry most of your traffic, and it's the only option for ranges and sorting, which we get to below.
The two GIN operator classes break a document into index entries differently, and every difference in the results follows from that.
The documentation describes it this way: jsonb_ops creates independent index items for each key and each value in the document. jsonb_path_ops creates items only for values, and each item is a hash of the value together with the keys leading to it.
That explains our numbers:
- Containment is more specific with
jsonb_path_ops. For@> '{"type": "signup"}',jsonb_opshas to look up the keytype, which appears in every row, and the valuesignup, then combine the two.jsonb_path_opslooks up one hash oftype+signup. For the single user that was 0.04 ms against 0.33 ms; forsignup, which matches 10,000 rows, the gap was smaller (5.6 ms against 9.8 ms above, 7.2 against 9.5 in a repeat run), because most of that time goes into reading the matching rows from the table. jsonb_path_opscan't answer "does this key exist?" There's no entry for a key on its own. Query 4 (payload ? 'coupon') took 4.75 ms withjsonb_opsand fell back to a 33.77 ms sequential scan withjsonb_path_ops. If you need key-exists checks, either keep the default class or write them as containment on a known value, as query 5 does.jsonb_path_opsis smaller and builds faster. 16 MB against 19 MB here, and 0.9 s against 3.1 s to build. The documentation says ajsonb_path_opsindex is usually much smaller; our documents have only a handful of keys, so the gap here is modest.- Empty structures are a blind spot. A document like
{"a": {}}contains no values, sojsonb_path_opscreates no entries for it, and the documentation warns that searching for such structures needs a full index scan.
Our default: start with jsonb_path_ops if your app filters by containment or jsonpath equality and never asks whether a key exists. Use the default jsonb_ops if it does.
Query 6 (payload @@ '$.user_id == 4714') used the GIN index under both operator classes. The same style of query with a comparison didn't:
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF)
SELECT count(*) FROM events WHERE payload @? '$.amount ? (@ > 490)';
Finalize Aggregate (actual rows=1 loops=1)
-> Gather (actual rows=3 loops=1)
Workers Planned: 2
Workers Launched: 2
-> Partial Aggregate (actual rows=1 loops=3)
-> Parallel Seq Scan on events (actual rows=269 loops=3)
Filter: (payload @? '$."amount"?(@ > 490)'::jsonpath)
Rows Removed by Filter: 333064That run had the jsonb_ops index in place. The documentation explains why it's ignored: for @? and @@, a GIN index extracts only clauses of the form accessors_chain == constant from the path and searches on those. >, < and like_regex are checked against each row, never looked up in the index: neither jsonb operator class can search a range. Query 7 never had a chance anyway, for the same reason as query 2: its operator is applied to (payload->>'amount')::numeric, not to payload.
For a range, an ORDER BY or a key you filter on constantly, index the value itself with a B-tree:
CREATE INDEX events_user_id ON events ((payload->>'user_id'));
CREATE INDEX events_amount ON events (((payload->>'amount')::numeric));With those two, query 2 took 0.03 ms and query 7 took 0.06 ms. The catch is that the query has to contain the indexed expression exactly, cast included. Three variants of "user 4714" against the text index:
-- uses events_user_id: same expression, text compared with text
EXPLAIN (COSTS OFF) SELECT count(*) FROM events WHERE payload->>'user_id' = '4714';
-- sequential scan: the cast makes it a different expression
EXPLAIN (COSTS OFF) SELECT count(*) FROM events WHERE (payload->>'user_id')::int = 4714;
-- sequential scan: -> returns jsonb, not text, so it's a different expression too
EXPLAIN (COSTS OFF) SELECT count(*) FROM events WHERE payload->'user_id' = '4714';Decide which form your application uses, write the index for that form, and keep it consistent in your ORM or query builder. If you need numeric comparisons on a key, index the cast (((payload->>'k')::numeric) or ::int) and query with the same cast.
@> compares JSON values with their JSON types. In our data user_id is a number, so:
SELECT count(*) FROM events WHERE payload @> '{"user_id": 4714}'; -- 15
SELECT count(*) FROM events WHERE payload @> '{"user_id": "4714"}'; -- 0No error, no warning, just zero rows. This bites when the JSON is written by more than one service, or when a client library serializes IDs as strings. ->> hides the difference because it always returns text, which is one reason people prefer it, and the reason it then needs its own index.
Only 4% of our rows have an amount. The full B-tree on (payload->>'amount')::numeric was 21 MB, as large as the primary key, because it also stores an entry for every row where the value is NULL. A partial index skips those rows:
DROP INDEX events_amount;
CREATE INDEX events_amount ON events (((payload->>'amount')::numeric))
WHERE (payload->>'amount')::numeric IS NOT NULL;
ANALYZE events;(On a live table, use DROP INDEX CONCURRENTLY and CREATE INDEX CONCURRENTLY so neither step blocks writes.)
It's 896 kB, and the planner uses it for query 7 because > 499 already implies IS NOT NULL. But the query got slower: 4 to 15 ms across our runs, instead of 0.06 ms with the full index. EXPLAIN ANALYZE shows why:
EXPLAIN (ANALYZE, TIMING OFF)
SELECT count(*) FROM events WHERE (payload->>'amount')::numeric > 499;
Finalize Aggregate (cost=25179.34..25179.35 rows=1 width=8) (actual rows=1 loops=1)
-> Gather (cost=25179.12..25179.33 rows=2 width=8) (actual rows=3 loops=1)
Workers Planned: 2
Workers Launched: 2
-> Partial Aggregate (cost=24179.12..24179.13 rows=1 width=8) (actual rows=1 loops=3)
-> Parallel Bitmap Heap Scan on events (cost=830.12..23831.90 rows=138889 width=0) (actual rows=26 loops=3)
Recheck Cond: (((payload ->> 'amount'::text))::numeric > '499'::numeric)
Heap Blocks: exact=79
-> Bitmap Index Scan on events_amount (cost=0.00..746.79 rows=333333 width=0) (actual rows=79 loops=1)
Index Cond: (((payload ->> 'amount'::text))::numeric > '499'::numeric)
Planning Time: 0.356 ms
Execution Time: 4.835 msThe planner expected 333,333 matching rows and found 79, so it started two parallel workers for a job that takes microseconds. When Postgres builds an index on an expression, ANALYZE also collects statistics on that expression, and the planner uses them to estimate how many rows a filter on it will match. Postgres only uses those statistics from non-partial indexes; a comment in the planner's source code (selfuncs.c) says partial indexes "probably don't reflect whole-relation statistics". ANALYZE still collects them, but with no usable statistics the planner falls back to a default guess, here one third of the table.
The fix, available since PostgreSQL 14, is to ask for statistics on the expression directly:
CREATE STATISTICS events_amount_stats ON ((payload->>'amount')::numeric) FROM events;
ANALYZE events;After that the estimate was close to reality (between 7 and 143 rows across our runs, against 79 actual; it moves because ANALYZE samples the table), the plan became a plain bitmap scan, and the query was back to 0.07–0.08 ms, with an index 24 times smaller than the full one:
Aggregate (cost=179.28..179.29 rows=1 width=8) (actual rows=1 loops=1)
-> Bitmap Heap Scan on events (cost=4.64..179.17 rows=45 width=0) (actual rows=79 loops=1)
Recheck Cond: (((payload ->> 'amount'::text))::numeric > '499'::numeric)
Heap Blocks: exact=79
-> Bitmap Index Scan on events_amount (cost=0.00..4.63 rows=45 width=0) (actual rows=79 loops=1)
Index Cond: (((payload ->> 'amount'::text))::numeric > '499'::numeric)
Planning Time: 0.168 ms
Execution Time: 0.117 msThe documentation describes this form of CREATE STATISTICS as "providing benefits similar to an expression index without the overhead of index maintenance".
Every index makes inserts slower; GIN indexes more than most, because one row produces many entries. We inserted the same 200,000 payloads into an empty copy of the table with one index at a time (plus the primary key), twice each:
- None — Insert time (ms): 290–322
- B-tree on user_id — Insert time (ms): 639–674
- GIN jsonb_path_ops — Insert time (ms): 669–722
- GIN jsonb_ops — Insert time (ms): 1,163–1,235
In this run the default GIN index roughly quadrupled the insert time, and jsonb_path_ops a bit more than doubled it. GIN softens part of this with its pending list: with fastupdate on (the default), new entries go into an unsorted list and are merged into the main index when the list grows past gin_pending_list_limit (4 MB by default) or when the table is vacuumed or autoanalyzed. That makes most inserts cheaper, but an occasional insert pays for the merge. For one-off bulk loads, the documentation suggests dropping the GIN index and recreating it afterwards.
If one key is in nearly every query, a stored generated column is often cleaner than an expression index:
ALTER TABLE events
ADD COLUMN user_id int GENERATED ALWAYS AS ((payload->>'user_id')::int) STORED;
CREATE INDEX events_user_id_col ON events (user_id);Queries say WHERE user_id = 4714, the type is enforced once at write time, and ORMs see an ordinary column. It costs some storage (our table grew from 154 MB to 158 MB) and the ALTER TABLE rewrites the whole table under an ACCESS EXCLUSIVE lock, which blocks reads as well as writes, so treat it like any other migration that locks a table.
- List the
WHEREclauses that actually hit the JSON column, not the keys you think are important. - Containment and jsonpath equality on many keys: one GIN index. Use
jsonb_path_opsunless you need?,?|,?&or the jsonpath wildcard accessors.*and.**. -
->>equality, ranges orORDER BYon a few keys: B-tree expression indexes, written with the same operator and cast as the query. - Keys that only some rows have: a partial index, plus
CREATE STATISTICSon the expression so the estimates stay right. - Check that your writers agree on JSON types (
4714vs"4714"). - Run
EXPLAIN (ANALYZE)on the real query before and after, and build indexes on a live table withCREATE INDEX CONCURRENTLY.
For index problems that aren't specific to JSON (mismatched types, functions on columns, LIKE with a leading wildcard), see why Postgres is not using your index.
Everything here is plain PostgreSQL 17; nothing needs an extension. The numbers that matter, though, are the ones from your own data: how many distinct keys your documents have, how selective your filters are, how big each index gets. On Relyt One the cheapest way to get them is a branch. It starts from the parent's data with copy-on-write storage and runs on its own compute, so you can build all three kinds of index, compare EXPLAIN (ANALYZE) output and index sizes, and throw the branch away, without adding load or locks to production.
The PostgreSQL manual covers the details in jsonb Indexing, GIN Indexes and CREATE STATISTICS.



