Sub topic 9
Speeding up array searches with GIN indexes
This chapter assumes you can write @>, && and = ANY queries against an array column, as covered in the previous chapters. It also assumes you can read basic EXPLAIN output. You will build a GIN index on an array column and see which queries it serves. You will also learn why the planner sometimes ignores it, and what it costs on writes.
Why a B-tree does not help
A default B-tree index on an array column treats the whole array as one value. It can answer tags = '{postgres,gin}' and it can sort arrays, but it knows nothing about the individual elements. A query such as tags @> ARRAY['postgres'] asks which rows contain a given element anywhere in the array, and a B-tree cannot answer that. Without a suitable index, PostgreSQL reads every row and checks the array.
A GIN index (Generalized Inverted Index) is built for this kind of question. It is an inverted index. Instead of mapping each row to its values, it maps each distinct element value to the list of rows that contain it. That list is called a posting list.
To find rows containing postgres, PostgreSQL looks up one key and reads its list of rows. To find rows containing both postgres and gin, it intersects two lists. The work depends on the number of matching rows, not on the table size.
Creating the index
Using the posts table from earlier in this tutorial:
CREATE INDEX posts_tags_gin ON posts USING gin (tags);
EXPLAIN SELECT title FROM posts WHERE tags @> ARRAY['postgres'];USING gin (tags) with no operator class picks the default one for arrays, array_ops. It works for any element type that has a B-tree operator class, which covers text, integer, bigint, uuid and the other common types.
On a table with a few rows, EXPLAIN will probably show a sequential scan. Reading two pages is cheaper than consulting an index, so the planner is correct. To see the index work, you need data.
Seeing the index used
This script builds a table with 100,000 rows. Each row has two common tags, and 10 rows also have the tag rare.
DROP TABLE IF EXISTS posts_big;
CREATE TABLE posts_big (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title text NOT NULL,
tags text[] NOT NULL DEFAULT '{}'
);
INSERT INTO posts_big (title, tags)
SELECT 'Post ' || g,
ARRAY['tag' || (g % 50), 'tag' || (100 + g % 7)]
FROM generate_series(1, 100000) AS g;
INSERT INTO posts_big (title, tags)
SELECT 'Rare post ' || g, ARRAY['tag1', 'rare']
FROM generate_series(1, 10) AS g;
CREATE INDEX posts_big_tags_gin ON posts_big USING gin (tags);
ANALYZE posts_big;
EXPLAIN
SELECT title FROM posts_big WHERE tags @> ARRAY['rare'];The plan should look like this. Costs and row estimates will differ on your machine.
Bitmap Heap Scan on posts_big (cost=... rows=10 width=...)
Recheck Cond: (tags @> '{rare}'::text[])
-> Bitmap Index Scan on posts_big_tags_gin (cost=... rows=10 width=0)
Index Cond: (tags @> '{rare}'::text[])Two details matter here.
- GIN indexes produce a bitmap of matching heap pages. They do not return rows one at a time, so you see
Bitmap Index Scanfollowed byBitmap Heap Scan. Recheck Condmeans PostgreSQL re-tests the condition on each fetched row. For arrays the recheck is cheap, and it guards against index entries that are only candidates.
Now try the common tag:
EXPLAIN
SELECT title FROM posts_big WHERE tags @> ARRAY['tag1'];About 2,010 of 100,010 rows contain tag1. The planner may still use the bitmap scan, or it may choose a sequential scan. Which one wins depends on your settings and statistics. The index pays off most when the search value is rare. As the matching fraction grows, reading the index and then most of the table costs more than a plain scan.
Which operators the index serves
The array_ops class supports four operators.
| Expression | Meaning | Uses the GIN index? |
|---|---|---|
| `tags @> ARRAY['a','b']` | contains all listed values | Yes |
| `tags <@ ARRAY['a','b','c']` | every element is in the list | Yes |
| `tags && ARRAY['a','b']` | shares at least one value | Yes |
| `tags = ARRAY['a','b']` | exactly equal | Yes |
| `'a' = ANY (tags)` | contains one value | No |
| `'a' <> ALL (tags)` | contains no copy of the value | No |
| `cardinality(tags) > 3` | has more than three elements | No |
The most common mistake is the ANY form. 'gin' = ANY (tags) is easy to read, but the planner does not translate it into an array operator. Rewrite it as tags @> ARRAY['gin'] to get the index:
-- Not indexable by a GIN index on tags
SELECT title FROM posts_big WHERE 'rare' = ANY (tags);
-- Indexable, and returns the same rows
SELECT title FROM posts_big WHERE tags @> ARRAY['rare'];The && operator does the same job for an "any of these" search over several values: tags && ARRAY['rare', 'tag2']. The index looks up each key and merges the lists.
Types must match
The right-hand array must have the same type as the column. For a bigint[] column, ARRAY[1,2] is an integer[], and the comparison fails with an "operator does not exist" error. Cast it:
CREATE TABLE docs (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
ids bigint[] NOT NULL DEFAULT '{}'
);
CREATE INDEX docs_ids_gin ON docs USING gin (ids);
SELECT id FROM docs WHERE ids @> ARRAY[1, 2]::bigint[];The same applies to varchar[] columns searched with text[] values. A cast that applies to the column side, such as tags::text[], hides the column from the index.
Edge cases in how GIN treats arrays
- Empty arrays.
tags @> '{}'is true for every row, because an empty set is contained in anything. The index cannot narrow that down, so expect a full scan. For<@, a row with an empty array matches any list. GIN handles this with a special placeholder entry for empty arrays, so such rows are still found. - NULL elements. A NULL inside an array never matches with
@>or&&, because the underlying=comparison yields NULL, not true.ARRAY[1, NULL] @> ARRAY[NULL]::int[]returns false. The index agrees with this behavior, so there is nothing to work around, but you cannot search for NULL elements with these operators. - Duplicates.
@>ignores how many times a value occurs.ARRAY['a'] @> ARRAY['a','a']is true. If you need counts, you needunnestandcount. - A NULL column. GIN does not help find rows where the whole array is NULL. The earlier
NOT NULL DEFAULT '{}'design avoids that case entirely.
What the index costs
A GIN index is large and slower to write than a B-tree. Three costs are worth measuring.
Size. A row with 20 elements creates up to 20 index entries. Check the size against the table:
SELECT pg_size_pretty(pg_relation_size('posts_big')) AS table_size,
pg_size_pretty(pg_relation_size('posts_big_tags_gin')) AS index_size;PostgreSQL compresses posting lists, so common values are cheap to store. Many distinct values with few rows each are not.
Insert and update time. Every insert touches one index entry per distinct element. To keep this fast, GIN uses a pending list, which is a small unsorted buffer of new entries that is merged into the main structure in batches. The fastupdate storage parameter controls it, and it is on by default. The batch size is governed by gin_pending_list_limit. Merging happens during VACUUM or when the list fills. Two consequences follow:
- Most inserts are fast, but an occasional one pays for a merge and takes noticeably longer.
- Searches must scan the pending list in addition to the main index, so a large list slows reads. If you need steady latency, you can turn the buffering off:
ALTER INDEX posts_big_tags_gin SET (fastupdate = off);Updates. Changing the tags value of a row writes a new row version and new index entries. PostgreSQL cannot use a heap-only tuple (HOT) update when an indexed column changes. A workload that frequently rewrites tags therefore produces more index churn and more vacuum work than one that mostly inserts and reads.
Combining an array filter with other conditions
Real queries rarely filter on tags alone. For WHERE author_id = 7 AND tags @> ARRAY['gin'], the planner can use a B-tree on author_id and the GIN index on tags separately. It combines the two bitmaps with a BitmapAnd node. This usually works well, and it means you do not need a special composite index.
If you want one index for both columns, the btree_gin extension adds GIN operator classes for scalar types:
CREATE EXTENSION IF NOT EXISTS btree_gin;
CREATE INDEX posts_author_tags_gin
ON posts_big USING gin (id, tags);This is a single index covering a scalar and an array. It is useful when the scalar condition is an equality. For ordering or range scans on the scalar, a B-tree is still the better tool. A partial index (CREATE INDEX ... WHERE published) is another way to keep the GIN index small when most queries touch only a subset of rows.
Diagnosing an index that is not used
When a query that should use the index does not, work through these checks in order.
- Check the operator. Confirm the query uses
@>,<@,&&or=, notANYorALL. - Check the types. Cast the right-hand array to the column's type. Do not cast the column.
- Check selectivity. If the value matches a large fraction of the table, a sequential scan may be the right choice.
- Refresh statistics. Run
ANALYZEafter a bulk load. Without it, row estimates can be badly off. - Test the index directly. In a session, disable sequential scans and compare:
SET enable_seqscan = off;
EXPLAIN ANALYZE SELECT title FROM posts_big WHERE tags @> ARRAY['tag1'];
RESET enable_seqscan;If the index plan is faster in EXPLAIN ANALYZE, the planner's cost estimates are off, and you should look at statistics and cost settings. If it is slower, the planner made the right call. Use enable_seqscan = off only for diagnosis, never as a permanent setting.
When GIN is the wrong tool
- If you need to sort or range-scan by an element, GIN cannot help, because it is unordered.
- If you filter on array length, create a B-tree expression index on
cardinality(tags). - If you need per-element metadata, such as who added a tag and when, or you need foreign keys on elements, a join table is the better design and it uses ordinary B-tree indexes. The next chapters compare the two designs.
Exercise
A table events(id bigint, codes integer[]) has a GIN index on codes. The query SELECT id FROM events WHERE 42 = ANY (codes); runs a sequential scan on a large table, even though few rows match. Rewrite the query so the index can be used, and explain why the original could not use it.
Show answer
Use SELECT id FROM events WHERE codes @> ARRAY[42];. The default GIN operator class for arrays supports @>, <@, && and =, and the planner does not turn = ANY (codes) into one of those operators, so the original could not use the index. If codes were bigint[], the right side would need a cast, ARRAY[42]::bigint[].
Exercise
You load 5 million rows into an array table, create a GIN index, and run EXPLAIN on a selective @> query. The plan estimates 1 row where hundreds match, and it picks a poor plan. What is the first thing to try?
Show answer
Run ANALYZE on the table so the planner has current statistics after the bulk load, then run EXPLAIN again. If the estimate is still wrong, compare plans with EXPLAIN ANALYZE while enable_seqscan is temporarily off.