Skip to main content
JSONB in Postgres from Node.js: How We Index It with GIN, jsonb_path_ops, and Expression Indexes — Field Notes

JSONB in Postgres from Node.js: How We Index It with GIN, jsonb_path_ops, and Expression Indexes — Field Notes

November 25, 2026
Backend Engineering
8 min read

Headline: A GIN index on a PostgreSQL jsonb column only serves the operators of its operator class (@>, ?, ?|, ?&, @?, @@), so a filter written as data->>'status' = 'paid' ignores it and scans the table. At Devya we index JSONB by query shape: containment through GIN with jsonb_path_ops, equality, ranges and sorts through B-tree expression indexes or STORED generated columns, and any field we filter on every request becomes a real column.

JSONB is the PostgreSQL column type that stores JSON in a decomposed binary format. Our team reaches for it when a Node.js or NestJS schema meets data whose shape we do not control: webhook payloads, per-tenant custom fields, and product attributes that differ by category. The failure we see most often in code reviews is not a wrong result. It is a correct query that stopped using an index once the table grew.

Key takeaways

jsonb over json: PostgreSQL jsonb stores parsed binary, drops whitespace and duplicate keys (the last value wins), and supports GIN indexing. The json type stores an exact copy of the input text.

GIN operators only: a GIN index on a jsonb column serves @>, ?, ?|, ?&, @? and @@. It does not serve data->>'key' = 'value', range filters, or ORDER BY.

jsonb_path_ops: the jsonb_path_ops operator class supports only @>, @? and @@, and its index is usually much smaller and more selective than the default jsonb_ops.

Ranges and sorts: a range filter or sort on a JSON field needs a B-tree expression index or a STORED generated column. PostgreSQL 18 cannot index VIRTUAL generated columns, and VIRTUAL is the PostgreSQL 18 default.

node-postgres arrays: the pg driver sends a JavaScript array parameter as a Postgres array literal, not JSON, so we pass JSON.stringify(value) with an explicit ::jsonb cast.

When should you use a jsonb column instead of regular columns?

We use jsonb for data we store and return as one unit, and regular columns for data we filter, join, sort, constrain or update on its own. The question we ask about each field is not whether it is JSON-shaped but whether any query touches that field by itself.

Third-party webhook payloads go into jsonb, often unindexed: someone else owns the shape, and we keep it for replay and audit.

Per-tenant custom fields go into jsonb with a GIN index: keys are unknown at migration time and filters are containment checks.

Status, tenant ID, timestamps and foreign keys stay regular columns: they are filtered on every request and need foreign keys, NOT NULL and real planner statistics.

Counters and frequently updated fields stay regular columns. Updating one key with jsonb_set() is not an in-place edit: PostgreSQL MVCC writes a new row version with the whole new jsonb value, and a value larger than about 2 kB is compressed and stored out of line by TOAST, so a counter inside a large document rewrites the document on every increment.

PostgreSQL also keeps statistics for a jsonb column as whole values, not per key, so row estimates for key filters are often rough guesses that lead to poor join plans.

Why does a GIN index ignore data->>'status' = 'paid'?

A GIN index is used only when the WHERE clause applies one of the index's operators directly to the indexed expression. The ->> operator extracts a field as text, and ->> followed by = is a text comparison, not a jsonb operator, so the planner falls back to a sequential scan even with CREATE INDEX orders_data_gin ON orders USING gin (data) in place.

We fix it in one of two ways. Rewriting the filter as containment, WHERE data @> '{"status": "paid"}', lets the existing GIN index serve it, and the same operator matches array elements: data @> '{"tags": ["urgent"]}' finds rows whose tags array contains "urgent". Keeping ->> and adding a B-tree expression index, CREATE INDEX orders_status_idx ON orders ((data->>'status')), also works when the query repeats the indexed expression exactly.

Containment is stricter about types than text extraction: {"total": 100} does not contain {"total": "100"}, while data->>'total' = '100' matches both. We confirm the plan with EXPLAIN (ANALYZE, BUFFERS) on a production-sized copy: a Bitmap Index Scan on the GIN index means it works, and a Seq Scan with a large Rows Removed by Filter means it does not.

Should you use jsonb_ops or jsonb_path_ops?

We use jsonb_path_ops unless a query needs the key-existence operators ?, ?| or ?&. An operator class tells an index which operators it can serve, and the two built-in GIN operator classes for jsonb trade coverage for size.

jsonb_ops (the default) serves ?, ?|, ?&, @>, @? and @@, and indexes each key and value as a separate item. We pick it when queries check whether keys exist.

jsonb_path_ops serves @>, @? and @@ only, and indexes a hash of each value with the path leading to it. We pick it for containment and JSONPath filters: CREATE INDEX orders_data_path_gin ON orders USING gin (data jsonb_path_ops).

We often index one subtree instead of the whole document, for example CREATE INDEX products_tags_gin ON products USING gin ((attributes -> 'tags')), which serves WHERE attributes -> 'tags' ? 'sale'. GIN indexes cost more on writes than B-tree indexes: with fastupdate on, the default, new entries go into a pending list merged by VACUUM, autovacuum, or when the list exceeds gin_pending_list_limit (4 MB by default), so an occasional insert pays for the merge. A smaller subtree index keeps that cost smaller.

How do you filter by range or sort on a field inside jsonb?

A range filter or ORDER BY on a JSON field needs a B-tree index over an expression that casts the field to its real type, because GIN indexes cannot answer greater-than or less-than comparisons and cannot return rows in order. CREATE INDEX orders_total_idx ON orders (((data->>'total')::numeric)) serves WHERE (data->>'total')::numeric > 500 ORDER BY (data->>'total')::numeric DESC.

Dates are the trap. Casting text to timestamptz depends on the session TimeZone and DateStyle settings, so PostgreSQL rejects it in an index expression with ERROR: functions in index expression must be marked IMMUTABLE, and the same immutability rule blocks it in a generated column. Timestamps we filter on go into a real timestamptz column written by the application.

When a JSON field is queried constantly, we promote it to a generated column so ORMs see a normal column: ALTER TABLE orders ADD COLUMN status text GENERATED ALWAYS AS (data->>'status') STORED, then a plain B-tree index on status.

We write STORED explicitly. PostgreSQL 18 added VIRTUAL generated columns, which are computed on read, and made VIRTUAL the default when neither keyword is given, and PostgreSQL 18 does not support indexes on virtual generated columns. Adding a STORED generated column rewrites the table under an ACCESS EXCLUSIVE lock, so we schedule it like any other blocking migration.

What does node-postgres do to jsonb values?

node-postgres, the pg package, parses json and jsonb result columns with JSON.parse and serializes parameters by JavaScript type: plain objects become JSON text, but arrays become Postgres array literals. An array bound to a jsonb parameter fails with invalid input syntax for type json, so in jsonb_set(data, $1, $2::jsonb) we pass the path ['tags'] as a normal array, because the path is text[], and the value as JSON.stringify(tags).

Numbers are the second trap. jsonb stores numbers as PostgreSQL numeric with arbitrary precision, and JSON.parse turns them into JavaScript numbers, so an identifier above Number.MAX_SAFE_INTEGER (2^53 − 1) comes back rounded. We store large identifiers inside jsonb as strings.

Types are the third. The $type() annotation on a Drizzle ORM jsonb column, with an OrderData type parameter, is compile-time only, and PostgreSQL does not validate jsonb shape on its own. We validate with a Zod schema at the write boundary and add CHECK constraints such as CHECK (jsonb_typeof(data) = 'object') and CHECK (data ? 'status'), so writes from scripts and other services are rejected too.

FAQ

Q: Should I use json or jsonb in PostgreSQL?

A: Use jsonb in almost every case, because jsonb supports GIN indexing and faster processing. Use json or text only when the exact input text, including key order, whitespace and duplicate keys, must be preserved, such as a raw webhook body kept for signature re-verification.

Q: Why is my PostgreSQL GIN index on jsonb not used?

A: The query most likely filters with ->> and =, which is a text comparison a GIN index cannot serve. Rewrite the filter as data @> '{"key": "value"}' or add a B-tree expression index on (data->>'key').

Q: Does a GIN index on jsonb help ORDER BY or range queries?

A: No. GIN indexes cannot return rows in sorted order or answer greater-than and less-than comparisons. Sorting or range-filtering on a JSON field needs a B-tree expression index with a cast, or an indexed STORED generated column.

Q: Can I index a virtual generated column in PostgreSQL 18?

A: No. PostgreSQL 18 does not support indexes on virtual generated columns, and VIRTUAL is the default when the column definition omits the keyword. Declare the column STORED to index it.

Q: How do I enforce a schema on a jsonb column?

A: PostgreSQL does not validate jsonb structure by itself. Validate in the application with a schema library such as Zod, and add CHECK constraints such as jsonb_typeof(data) = 'object' and data ? 'key' so every write path is covered.