Sub topic 8
Indexing JSON: GIN Operator Classes and Expression Indexes
This chapter assumes that you know basic PostgreSQL SELECT statements, WHERE clauses, and CREATE INDEX. You should also understand that jsonb stores JSON data in a binary format that PostgreSQL can inspect and index.
A JSON index is useful only when your queries use an expression supported by that index. Indexing the whole document does not automatically make every JSON operation fast.
Use GIN for document searches
A GIN index, or Generalized Inverted Index, stores many searchable values from one row. It fits jsonb documents because one document can contain many keys, values, and array elements.
The default GIN operator class is jsonb_ops:
CREATE INDEX orders_details_gin
ON orders
USING gin (details);This index supports a broad set of JSONB operators, including containment and key existence:
SELECT id
FROM orders
WHERE details @> '{"status": "paid"}'::jsonb;
SELECT id
FROM orders
WHERE details ? 'shipping';For a containment-heavy workload, jsonb_path_ops can create a smaller and often faster index:
CREATE INDEX orders_details_path_gin
ON orders
USING gin (details jsonb_path_ops);jsonb_path_ops supports containment with @> and SQL/JSON path matching with operators such as @? and @@. It does not support every operator supported by the default class, especially the top-level key-existence operators.
| Operator class | Typical strengths | Important limitation | Column |
|---|---|---|---|
| `jsonb_ops` | Broad operator support, including `@>`, `?`, `? | `, and `?&` | Usually larger than `jsonb_path_ops` |
| `jsonb_path_ops` | Compact indexes for containment and path queries | Cannot support all key-existence queries |
Choose jsonb_ops when you need varied JSON operators. Choose jsonb_path_ops when most important queries test document containment and index size matters.
Index one extracted value
A whole-document GIN index is not always the best choice. If your application often filters by one field, create an expression index on that extracted value:
CREATE INDEX orders_status_idx
ON orders ((details ->> 'status'));The expression uses double parentheses because the indexed value is an expression rather than a simple column name. Queries using the same expression can use this index:
SELECT id, customer
FROM orders
WHERE details ->> 'status' = 'paid';The expression returns text. If you filter by a numeric JSON value, include the cast in both the index and the query:
CREATE INDEX orders_total_idx
ON orders (((details ->> 'total')::numeric));
SELECT id
FROM orders
WHERE (details ->> 'total')::numeric >= 40;An expression index is usually smaller and more targeted than a GIN index. It is a good choice when the set of frequently queried JSON fields is known. It also avoids indexing every key and array value in every document.
The trade-off is maintenance. PostgreSQL must update each relevant index whenever a row changes. A large GIN index can increase write cost and consume considerable disk space. Several expression indexes can also add write overhead, although each one targets a narrower value.
Check the query plan
Use EXPLAIN to inspect the plan PostgreSQL selects:
EXPLAIN
SELECT id
FROM orders
WHERE details @> '{"status": "paid"}'::jsonb;Look for an index-related node such as Bitmap Index Scan, Bitmap Heap Scan, or Index Scan. A Seq Scan means PostgreSQL chose to read the table directly. That can be correct for a small table or a condition that matches many rows.
After loading or changing a substantial amount of data, refresh statistics:
ANALYZE orders;For actual execution times and row counts, use EXPLAIN (ANALYZE, BUFFERS). Use it carefully on write statements because ANALYZE executes the query.
Practical indexing decisions
Start with the queries your application actually runs. Index only predicates that are frequent or expensive enough to justify their storage and write cost.
- Use a GIN index for searches across varying keys, nested objects, and arrays.
- Use
jsonb_path_opswhen containment queries dominate and key-existence operators are unnecessary. - Use an expression index for a stable, frequently filtered field.
- Keep the expression and its casts consistent between the index and the query.
- Run
EXPLAINon representative data instead of assuming an index will be used.
Exercise
Which index is more appropriate for WHERE details ->> 'status' = 'paid': a whole-document GIN index or an expression index on details ->> 'status'?
Show answer
The expression index is usually more targeted and smaller because it indexes only the extracted status value. Confirm the choice with EXPLAIN on representative data.