Sub topic 7
GIN: Indexing `jsonb`, Arrays, and Full-Text Search
Prerequisites and the GIN model
This chapter assumes you know basic SELECT, WHERE, and CREATE INDEX statements. You should also know the PostgreSQL jsonb, array, and text data types.
GIN stands for Generalized Inverted Index. A GIN index maps individual pieces of a value to the table rows that contain those pieces. For example, a JSON document can contribute keys and values, an array can contribute its elements, and a full-text document can contribute searchable lexemes.
A B-tree usually stores one ordered index key for each row. A GIN index stores many index entries for one row because one row can contain many keys, array elements, or words.
GIN is useful when a query asks whether a larger value contains a requested part. The index first finds candidate rows for each part. PostgreSQL then checks the table rows when necessary, because some index entries are lossy or do not contain the complete original value.
GIN for `jsonb`
A default GIN index on a jsonb column supports containment queries with the @> operator:
CREATE TABLE events (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
payload jsonb NOT NULL
);
INSERT INTO events (payload) VALUES
('{"type": "login", "user_id": 42, "source": "web"}'),
('{"type": "purchase", "user_id": 7, "amount": 19.99}');
CREATE INDEX events_payload_gin_idx
ON events USING gin (payload);
SELECT id
FROM events
WHERE payload @> '{"type": "login"}';The query asks whether payload contains the specified JSON structure. It does not ask whether the whole document equals that structure.
PostgreSQL also provides the jsonb_path_ops operator class. It stores a smaller, more specialized representation and can make @> searches smaller or faster in suitable workloads:
CREATE INDEX events_payload_path_idx
ON events USING gin (payload jsonb_path_ops);The default jsonb_ops operator class supports more jsonb operators. jsonb_path_ops focuses mainly on containment. Choose it only after confirming that your queries use the operators it supports.
A common error is indexing the column but applying a function that does not match the indexed expression. An index on payload does not automatically support every expression involving payload. Test the actual query with EXPLAIN.
GIN for arrays
GIN can index array elements. The containment operators @> and <@, and array overlap operator &&, are common examples:
CREATE TABLE articles (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
tags text[] NOT NULL
);
CREATE INDEX articles_tags_gin_idx
ON articles USING gin (tags);
SELECT id
FROM articles
WHERE tags @> ARRAY['postgres', 'indexing'];
SELECT id
FROM articles
WHERE tags && ARRAY['postgres', 'mysql'];The first query finds rows containing both requested elements. The second finds rows sharing at least one element.
GIN does not make every array operation fast. A query that transforms the array, searches for a position, or uses an unsupported expression may require a sequential scan. The indexed expression and the query expression must match.
GIN for full-text search
Full-text search converts text into a tsvector, a normalized collection of searchable lexemes. A tsquery describes the terms and relationships to find. The match operator is @@.
Create an expression index when queries repeatedly apply the same conversion:
CREATE TABLE documents (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
body text NOT NULL
);
CREATE INDEX documents_body_fts_idx
ON documents
USING gin (to_tsvector('english', body));
SELECT id
FROM documents
WHERE to_tsvector('english', body)
@@ to_tsquery('english', 'postgres & indexing');The configuration name, english in this example, matters. It controls stemming, stop words, and tokenization. The query should use the same configuration as the indexed expression.
For larger applications, a stored tsvector column can make the indexed form explicit. Triggers or application code must keep that column synchronized when the source text changes.
Plans, limitations, and maintenance
Use EXPLAIN (ANALYZE, BUFFERS) to check the real plan:
EXPLAIN (ANALYZE, BUFFERS)
SELECT id
FROM events
WHERE payload @> '{"type": "login"}';Look for a Bitmap Index Scan followed by a Bitmap Heap Scan, or an index scan using the GIN index. PostgreSQL may still choose a sequential scan when the table is small, many rows match, statistics are stale, or the index cost is higher than reading the table directly.
GIN indexes can be large. Inserts and updates may be more expensive because PostgreSQL must maintain multiple entries per row. Index builds and heavy update workloads can also create pending entries that are later merged. Regular vacuuming and current statistics help the planner and maintenance process.
Choosing the operator class
The operator class determines which operators the index can support and how values are represented. For jsonb, compare jsonb_ops with jsonb_path_ops. For full-text search, index the exact to_tsvector expression. Always test representative queries instead of choosing from index names alone.
Exercise
You have a jsonb column named metadata, and the main query is metadata @> '{"active": true}'. Which index type and operator class are a sensible starting point?
Show answer
Create a GIN index on metadata with the default jsonb_ops operator class. Consider jsonb_path_ops only if the workload is primarily supported containment queries and testing shows its smaller representation helps.