In PostgreSQL, how do the GIN operator classes jsonb_ops and jsonb_path_ops differ, and when would you choose jsonb_path_ops?
answer
- default class versus named class
- keys and values, or paths
- a hash of the path to a value
- what a key-exists test needs
basics
~20 sjsonb_ops, the default, indexes every key and value separately and serves ?, ?|, ?&, @>, @? and @@. jsonb_path_ops stores one hash per value including its key path, serves only @>, @? and @@, and is usually smaller and more selective.
solid answer
~50 sA plain `CREATE INDEX ... USING gin (payload)` uses `jsonb_ops`, which emits a separate index item for every key and every value in each document. It supports the key-exists operators `?`, `?|` and `?&` as well as containment `@>` and the jsonpath matches `@?` and `@@`. `jsonb_path_ops` must be named, as in `USING gin (payload jsonb_path_ops)`. Each of its items is a hash of one value together with the keys leading to it, so `payload @> '{"qc": "suspect"}'` looks up one specific item instead of intersecting the row lists for `qc` and `suspect`. That index is usually much smaller and faster, but it cannot answer key-exists tests and has no entries for empty structures such as `{"a": {}}`. Choose it when the workload is containment; keep `jsonb_ops` when you test whether keys exist. Neither class serves `payload->>'qc' = 'suspect'`.
code
sql · 13 linesCREATE INDEX readings_payload_pgin ON readings
USING gin (payload jsonb_path_ops);
-- served: containment on the indexed column
SELECT station_id, observed_at
FROM readings
WHERE payload @> '{"qc": "suspect"}';
-- not served by jsonb_path_ops: key existence needs jsonb_ops
SELECT count(*) FROM readings WHERE payload ? 'gust_kmh';
-- served by neither class: ->> with = is not a GIN operator
SELECT count(*) FROM readings WHERE payload->>'qc' = 'suspect';go deeper
Recall that jsonb is usually indexed with GIN, that the default class is jsonb_ops, and that @> containment is the query shape the index is built for.
Explain the storage difference: jsonb_ops indexes keys and values separately, jsonb_path_ops hashes each value with its path, and say which operators each one loses or keeps.
Choose the class from the operators the application really sends, spot ->> filters that no GIN index serves, and reach for expression indexes on hot paths to cut size and write cost.
Weigh a flexible whole-document index against several narrow expression indexes as the payload schema drifts, counting write amplification on an insert-heavy table against query coverage.
## Two operator classes for one data type A GIN index does not index a `jsonb` document as one value. The **operator class** breaks each document into **keys** (index items), and GIN stores each item once with the set of rows that contain it. PostgreSQL ships two GIN operator classes for `jsonb`, and they break a document up differently: - **`jsonb_ops`** is the **default**. `CREATE INDEX readings_payload_gin ON readings USING gin (payload);` uses it. - **`jsonb_path_ops`** must be named: `USING gin (payload jsonb_path_ops)`. Take a reading whose `payload` is `{"qc": "suspect", "sensor": {"model": "WX-200"}}`. ## What jsonb_ops stores `jsonb_ops` creates an **independent item for every key and every value**: `qc`, `suspect`, `sensor`, `model` and `WX-200` each become an entry. To answer `payload @> '{"qc": "suspect"}'`, the index fetches the rows containing `qc` and the rows containing `suspect`, intersects them, and rechecks the candidates. Because keys are indexed on their own, the class can also answer whether a key exists anywhere at the top level of a document, with `?`, `?|` and `?&`. The cost shows up when a key appears in nearly every document. If every reading has a `qc` key, the item for `qc` matches every row, and the search depends entirely on how rare the value is. ## What jsonb_path_ops stores `jsonb_path_ops` creates **one item per value**, and that item is a **hash of the value together with the keys leading to it**. The nested value above yields a single item that folds `sensor`, `model` and `WX-200` into one hash. A containment query for `{"sensor": {"model": "WX-200"}}` therefore looks up exactly one, highly specific item. The trade-offs follow from that design: - The index is **usually much smaller** than a `jsonb_ops` index over the same data. - Searches are **more selective**, especially when the keys involved appear in most documents. - It **cannot test whether a key exists**, because no item represents a key on its own. - It produces **no entries for structures without values**, such as `{"a": {}}`; a search for one needs a full-index scan, which is slow. - For jsonpath, `jsonb_ops` also supports the `.*` and `.**` accessors; `jsonb_path_ops` does not. ## Operators each class serves | Operator | Meaning | `jsonb_ops` | `jsonb_path_ops` | |---|---|---|---| | `@>` | contains this jsonb | yes | yes | | `@?` | jsonpath returns any item | yes | yes | | `@@` | jsonpath predicate is true | yes | yes | | `?` | top-level key or element exists | yes | no | | `?\|` | any of these keys exists | yes | no | | `?&` | all of these keys exist | yes | no | For `@?` and `@@`, GIN extracts only clauses of the form `accessor chain == constant` from the jsonpath; a range test such as `@ > 80` cannot be answered from either index. ## Queries neither class serves A GIN index on `payload` serves operators applied **directly to `payload`**. These do not qualify: 1. `payload->>'qc' = 'suspect'` extracts text and compares it with `=`, which is not a GIN `jsonb` operator. Rewrite it as `payload @> '{"qc": "suspect"}'`, or index the expression with a B-tree. 2. `payload -> 'flags' ? 'icing'` applies `?` to a sub-expression, not to the indexed column. An expression index `USING gin ((payload -> 'flags'))` serves it, and it is smaller because it stores only what sits under `flags`. ## Choosing for the readings payload 1. List the operators the application actually sends. If every filter is containment or a jsonpath equality, choose **`jsonb_path_ops`**. 2. If any query tests key existence with `?`, `?|` or `?&`, keep **`jsonb_ops`**, or add a small expression index for that one key. 3. If one path dominates, an expression index on that path, GIN or B-tree, may beat both. 4. Confirm with `EXPLAIN (ANALYZE)` that the plan shows a Bitmap Index Scan on the index you built. 5. Compare sizes with `pg_relation_size('readings_payload_pgin')` or `\di+` in `psql`. On an insert-heavy table such as `readings`, a smaller index also means less work per insert, because every document adds one GIN entry per extracted item. Whatever the class, a GIN index on `payload` is maintained on every insert, so the write side matters as much as the read side on this table; the GIN pending list, controlled by `fastupdate`, is how PostgreSQL defers that work.
- The filters always look inside payload -> 'flags'. Why might an expression GIN index beat a whole-column one?A GIN index on `payload` stores items for every key and value in every document, while `USING gin ((payload -> 'flags'))` stores only what sits under `flags`, so it is smaller and quicker to search and update. It also lets `payload -> 'flags' ? 'icing'` use an index, because the operator is applied to exactly the indexed expression. The price is that it serves nothing outside `flags`.
- Can a GIN index on payload answer payload @? '$.gust_kmh ? (@ > 80)' from the index alone?No. For `@?` and `@@`, GIN extracts only `accessor chain == constant` clauses from the jsonpath and searches on those keys and values. A numeric range test gives the index nothing specific to look up, so the comparison is evaluated against the rows. For frequent numeric range filters, index the extracted value, for example a B-tree on `((payload->>'gust_kmh')::numeric)`.
- jsonb_path_ops is the default operator class for a GIN index on jsonb.
- A jsonb_path_ops index can answer payload ? 'gust_kmh'.
- A GIN index on payload makes payload->>'qc' = 'suspect' fast.
- jsonb_path_ops indexes only top-level keys and ignores nested objects.
- jsonb_path_ops is smaller because it compresses each document before indexing.