Sub topic 8
Indexing JSON: GIN operator classes and expression indexes
This chapter shows how to make jsonb queries fast. It covers two tools: GIN indexes, which index the whole document, and expression indexes, which index one value you extract from it. It assumes you can read EXPLAIN output at a basic level, know what a B-tree index is, and have the orders table from the earlier chapters, with a details jsonb column. Everything here needs PostgreSQL 12 or later.
Why a plain index does not help
A normal B-tree index on a jsonb column compares whole documents. It can serve details = '{...}', but it cannot help with details @> '{"status": "paid"}' or details ->> 'status' = 'paid'. Without a better index, PostgreSQL reads every row and parses the document.
You have two options:
- Index the whole document with a GIN (Generalized Inverted Index). It stores each key or value found in the documents and the rows that contain it.
- Index an expression such as
(details ->> 'status'). This is an ordinary B-tree over one extracted value.
The json type has no GIN operator class. To index json data, use an expression index that casts to jsonb, or switch the column to jsonb.
Setting up realistic test data
On a two-row table the planner always chooses a sequential scan, so you cannot see an index being used. Load enough rows for the plan to be meaningful. This script removes the two sample rows, then adds 100,000 generated orders in which about 1 in 1,000 is refunded.
TRUNCATE orders RESTART IDENTITY;
INSERT INTO orders (customer, details)
SELECT 'cust' || n,
jsonb_build_object(
'status', CASE WHEN n % 1000 = 0 THEN 'refunded'
ELSE (ARRAY['paid','pending','shipped'])[1 + n % 3] END,
'total', round((n % 500)::numeric / 3, 2),
'items', jsonb_build_array(
jsonb_build_object('sku', 'A' || (n % 20), 'qty', 1 + n % 3)),
'shipping', jsonb_build_object(
'city', (ARRAY['Oslo','Bergen','Trondheim'])[1 + n % 3])
)
FROM generate_series(1, 100000) AS n;
ANALYZE orders;Run ANALYZE after bulk loads. The planner needs fresh statistics to decide whether an index is worth using.
GIN indexes and the two jsonb operator classes
A GIN index is built with an operator class, which decides what gets stored and which operators the index supports. For jsonb there are two.
| Operator class | Stores | Supported operators | Notes | Column |
|---|---|---|---|---|
| `jsonb_ops` (default) | Every key and every value as a separate entry | `@>`, `?`, `?\ | `, `?&`, `@?`, `@@` | More flexible, larger index |
| `jsonb_path_ops` | A hash of each path from the root to a value | `@>`, `@?`, `@@` | Smaller and usually faster for `@>`, no key-existence operators |
Creating each kind:
-- Default class: supports containment AND key-existence operators
CREATE INDEX orders_details_gin_ops ON orders USING gin (details);
-- jsonb_path_ops: containment and jsonpath only
CREATE INDEX orders_details_gin ON orders USING gin (details jsonb_path_ops);Because jsonb_path_ops hashes the whole path to each value, a query like details @> '{"shipping": {"city": "Oslo"}}' matches one hashed entry. With jsonb_ops the same query looks up the keys and values separately and combines the results. That is why jsonb_path_ops is smaller and faster for containment.
The trade-off is that jsonb_path_ops cannot answer ?, ?|, or ?&, because it does not store keys on their own. It also handles poorly any search for an empty structure such as details @> '{"shipping": {}}'. That search needs a full index scan.
Compare the sizes on your own data:
SELECT pg_size_pretty(pg_relation_size('orders_details_gin_ops')) AS jsonb_ops,
pg_size_pretty(pg_relation_size('orders_details_gin')) AS jsonb_path_ops;On this data set jsonb_path_ops should be noticeably smaller. The exact sizes depend on your version and data.
Checking that the index is used
EXPLAIN (ANALYZE, BUFFERS)
SELECT id FROM orders WHERE details @> '{"status": "refunded"}';A healthy plan looks like this, with timings and costs that will differ:
Bitmap Heap Scan on orders
Recheck Cond: (details @> '{"status": "refunded"}'::jsonb)
-> Bitmap Index Scan on orders_details_gin
Index Cond: (details @> '{"status": "refunded"}'::jsonb)GIN indexes are read through a bitmap scan. The index returns a set of candidate row locations, and PostgreSQL then fetches those rows and rechecks the condition. Seeing Bitmap Index Scan means the index is working.
If you see Seq Scan on a large table, check three things:
- The operator in your query must be one the index supports.
- The value must be selective. If 40% of rows match, scanning the table is cheaper than using the index.
- Statistics must be fresh (
ANALYZE).
For a quick experiment you can run SET enable_seqscan = off; in your session. This only shows whether the index can be used. Never leave it set in production.
Which queries a GIN index can serve
The index supports operators, not arbitrary expressions. This is the most common mistake with JSON indexes.
-- Can use GIN (@> on the indexed column):
SELECT id FROM orders WHERE details @> '{"status": "refunded"}';
-- Cannot use GIN: ->> extracts a text value, and the index does not know about it
SELECT id FROM orders WHERE details ->> 'status' = 'refunded';Both queries return the same rows, but only the first can use the GIN index. When you want index support, write the filter as containment.
The same rule applies to jsonpath. The function jsonb_path_query is a set-returning function and cannot use an index. The operators @? (path returns something) and @@ (path predicate is true) can.
-- Index-supported with jsonb_ops or jsonb_path_ops
SELECT id FROM orders
WHERE details @? '$.items[*] ? (@.qty > 2)';
SELECT id FROM orders
WHERE details @@ '$.status == "refunded"';Be careful here: the index can narrow down candidates for some path expressions, but for others, such as numeric comparisons, it cannot narrow much. It then returns many candidates and PostgreSQL rechecks each one. Always confirm with EXPLAIN.
Expression indexes on one extracted value
If you filter on one key again and again, a B-tree on that key is smaller and faster than a GIN index. It also supports equality, ranges, and sorting, which GIN does not.
CREATE INDEX orders_status_idx ON orders ((details ->> 'status'));The double parentheses are required. The inner pair is the expression, and the outer pair is the index column list.
The query must use the same expression as the index, or the planner cannot match them:
-- Uses orders_status_idx
SELECT id FROM orders WHERE details ->> 'status' = 'refunded';
-- Does not use it: a different expression
SELECT id FROM orders WHERE details -> 'status' = '"refunded"';Indexing a number
->> returns text, so the index would sort numbers as strings ('10' before '9'). To get numeric ordering and range scans, cast inside the index and use the same cast in queries:
CREATE INDEX orders_total_idx ON orders (((details ->> 'total')::numeric));
SELECT id, (details ->> 'total')::numeric AS total
FROM orders
WHERE (details ->> 'total')::numeric > 160
ORDER BY (details ->> 'total')::numeric DESC
LIMIT 10;A bad value would make the cast fail during a write, because index expressions run on every insert and update. Combine this with the CHECK constraints covered in a later chapter if the data is not fully trusted.
Partial indexes
A partial index covers only the rows that match a WHERE clause. It is much smaller when you only query a rare subset:
CREATE INDEX orders_refunded_idx ON orders (id)
WHERE details @> '{"status": "refunded"}';The planner uses this index only when the query's WHERE clause implies the index predicate.
Indexing a sub-document
You can also build a GIN index on a piece of the document. This gives you key-existence support for a nested object, which a top-level jsonb_path_ops index lacks:
CREATE INDEX orders_shipping_gin ON orders USING gin ((details -> 'shipping'));
SELECT id FROM orders WHERE details -> 'shipping' ? 'city';The query repeats details -> 'shipping' exactly. A smaller indexed value means a smaller index.
Choosing an index
The decision depends on the shape of your queries.
A summary of the trade-offs:
- An expression index is the smallest and fastest choice for one key. It supports sorting and ranges. It helps only queries that repeat the exact expression.
jsonb_path_opssuits flexible containment searches over many keys. It is small and fast, but it has no key-existence support.jsonb_opsis the general choice. It costs more space.
Costs of indexing
Indexes are not free. Each one adds work to every write, and GIN indexes are especially costly to update, because one document produces many index entries.
- GIN uses a pending list to batch inserts (
fastupdate, on by default). Writes are faster, but a query must also scan the pending list, and an occasional insert pays for flushing it.VACUUMalso flushes it. You can adjust this withgin_pending_list_limit, but start with the defaults. - Updating any part of a jsonb value rewrites the whole value. If the document is indexed with GIN, the new version needs new index entries too, and PostgreSQL's heap-only tuple (HOT) optimization generally cannot apply when an indexed column changes. Frequently updated documents with large GIN indexes can bloat quickly.
- Create only the indexes your queries use. You can see how often each index is used with
pg_stat_user_indexes(theidx_scancolumn).
SELECT indexrelname, idx_scan
FROM pg_stat_user_indexes
WHERE relname = 'orders';Common errors
- The index exists but is not used. The query uses
->>while the index is GIN, or the expression differs from the index expression by a cast or an extra operator. ?fails with ajsonb_path_opsindex. The query still runs, but without index support. Usejsonb_opsor an expression index.syntax errorwhen creating an expression index. You left out the parentheses around the expression.- A text-ordered numeric index. You indexed
details ->> 'total'without a cast, and the query compares numbers. - Testing on a tiny table. The planner picks a sequential scan because it really is cheaper. Test with realistic row counts.
Exercise
A reporting query runs WHERE details ->> 'status' = 'paid' ORDER BY (details ->> 'total')::numeric DESC LIMIT 20 on a 5-million-row table, and a GIN index with jsonb_path_ops already exists on details. EXPLAIN shows a sequential scan. Which index should you add, and why does the GIN index not help?
Show answer
The GIN index cannot help because the filter uses ->> equality, not an operator that GIN supports (@>, ?, @?, @@), and GIN cannot provide sorted output. Add a B-tree expression index on the extracted values, for example CREATE INDEX ON orders ((details ->> 'status'), ((details ->> 'total')::numeric) DESC);, and keep the query expressions identical to the index expressions. Alternatively, rewrite the filter as details @> '{"status": "paid"}' to use GIN, but the sort would still need a separate step.
Exercise
You created CREATE INDEX idx ON orders USING gin (details jsonb_path_ops);. Will SELECT id FROM orders WHERE details ? 'tracking'; use it? What should you change?
Show answer
No. jsonb_path_ops does not support the ? operator, so PostgreSQL falls back to a sequential scan. Create the index with the default operator class (USING gin (details)), or create an expression index on the specific key, for example a B-tree on ((details ->> 'tracking')) with a query on IS NOT NULL, or a partial index WHERE details ? 'tracking'.