GIN indexes enable PostgreSQL to search values inside composite items, including words in full-text documents, elements in arrays, and keys and values in JSONB. This post shows how GIN indexes speed up these searches.
This is the first post in a three-part series on PostgreSQL inverted indexes:
- Three Typical GIN Index Use Cases in PostgreSQL
- How RUM Overcomes GIN’s Limitations in PostgreSQL Full-Text Search
- The Cost of Maintaining GIN and RUM Indexes in PostgreSQL
How a GIN Index Works
GIN (Generalized Inverted Index) indexes individual elements within composite items rather than the composite items themselves.
Let’s see how a GIN index works with tsvector (short for “text search vector”), a special PostgreSQL data type used to represent text for full-text search.
PostgreSQL’s to_tsvector function converts ordinary text into tsvector values for full-text search. The examples below show its output for two sentences:
postgres=# SELECT to_tsvector('simple', 'Rivers carry boats'); to_tsvector-------------------------------- 'boats':3 'carry':2 'rivers':1(1 row)postgres=# SELECT to_tsvector('simple', 'Boats cross rivers'); to_tsvector-------------------------------- 'boats':1 'cross':2 'rivers':3(1 row)
Here, to_tsvector() function converts ordinary text into a tsvector. The simple configuration lowercases the words. PostgreSQL displays the resulting lexemes in alphabetical order. The number after each lexeme shows its position in the original text: rivers is at position 1, carry at position 2, and boats at position 3.
The following diagram conceptually shows the GIN index entries for these two tsvector values.

Across both vectors, there are six lexeme occurrences and four distinct lexemes: boats, carry, cross, and rivers. A GIN index stores each distinct lexeme as a key and associates it with a posting list: a sorted list of heap TIDs for rows containing that lexeme. A TID (tuple identifier) is written as (block number, tuple offset). In this example, (0,1) and (0,2) identify tuples at offsets 1 and 2 on block 0.
If a posting list is too large to store inline, GIN stores it in a posting tree and keeps a pointer to that tree.
GIN is called an inverted index because it maps each key to the items that contain it. To see what makes this mapping “inverted,” compare it with the corresponding forward index, which maps each item to its keys:
TID (0,1) -> [boats, carry, rivers]TID (0,2) -> [boats, cross, rivers]
This inverted structure is best suited to highly repetitive keys, such as words in natural-language text or values in denormalized documents. For high-cardinality keys such as UUIDs or sequence numbers, it offers little advantage over a B-tree.
Preparing the Sample Data
To see how this inverted structure speeds up searches, we first prepare a film dataset for the three use cases below.
We create a table called films to store information about films. In this table, we define a generated column named tsv with the tsvector data type. PostgreSQL automatically builds its value from each film’s title, category, and actor names.
CREATE UNLOGGED TABLE films ( id serial PRIMARY KEY, title text NOT NULL, release_date timestamp without time zone NOT NULL, category text NOT NULL, actors_names text NOT NULL, tsv tsvector GENERATED ALWAYS AS ( to_tsvector('simple', title || ' ' || category || ' ' || actors_names) ) STORED);
Next, we populate films with three million rows. Each film has a four-letter title, a category, and three actor names. The titles and actor names are generated from random letters, and PostgreSQL automatically generates a tsv value for each row. Because the data is random, the matches may differ when you rerun the script.
TRUNCATE TABLE films RESTART IDENTITY;DROP INDEX IF EXISTS films_tsv_gin_idx;DROP INDEX IF EXISTS films_actors_gin_idx;WITH film_seed AS MATERIALIZED ( SELECT film_no, (current_date - floor(random() * 3650)::int)::timestamp AS release_date, (ARRAY['war', 'action', 'love', 'documentary', 'drama']) [floor(random() * 5)::int + 1] AS category, 3 AS actor_count FROM generate_series(1, 3000000) AS f(film_no)),title_chars AS ( SELECT f.film_no, c.char_no, chr(floor(random() * 26)::int + 97) AS letter FROM film_seed AS f CROSS JOIN generate_series(1, 4) AS c(char_no)),titles AS ( SELECT film_no, string_agg(letter, '' ORDER BY char_no) AS title FROM title_chars GROUP BY film_no),actor_names AS ( SELECT f.film_no, a.actor_no, initcap(first_name.name) || ' ' || initcap(last_name.name) AS actor_name FROM film_seed AS f CROSS JOIN LATERAL generate_series(1, f.actor_count) AS a(actor_no) CROSS JOIN LATERAL ( SELECT string_agg(chr(floor(random() * 26)::int + 97), '' ORDER BY c.char_no) AS name FROM generate_series(1, 3 + floor(random() * 6)::int + a.actor_no * 0 + f.film_no * 0) AS c(char_no) ) AS first_name CROSS JOIN LATERAL ( SELECT string_agg(chr(floor(random() * 26)::int + 97), '' ORDER BY c.char_no) AS name FROM generate_series(1, 3 + floor(random() * 6)::int + a.actor_no * 0 + f.film_no * 0) AS c(char_no) ) AS last_name),film_actors AS ( SELECT film_no, string_agg(actor_name, ', ' ORDER BY actor_no) AS actors_names FROM actor_names GROUP BY film_no)INSERT INTO films (title, release_date, category, actors_names)SELECT t.title, f.release_date, f.category, a.actors_namesFROM film_seed AS fJOIN titles AS t USING (film_no)JOIN film_actors AS a USING (film_no)ORDER BY f.film_no;
After populating the films table, we inspect a sample row to see what the data looks like:
postgres=# SELECT * FROM films LIMIT 1; id | title | release_date | category | actors_names | tsv----+-------+---------------------+----------+---------------------------------------------+-------------------------------------------------------------------------------------- 1 | xped | 2021-11-07 00:00:00 | drama | Nqetiw Fdgli, Dbfjxr Uaqtmxw, Pyikq Absvnaz | 'absvnaz':8 'dbfjxr':5 'drama':2 'fdgli':4 'nqetiw':3 'pyikq':7 'uaqtmxw':6 'xped':1(1 row)postgres=# select count(*) from films; count--------- 3000000(1 row)
GIN for Full-Text Search
We first search for rows whose tsv contains both drama and yuan. The simple configuration normalizes 'DRAMA & YUAN' to lowercase lexemes, and the & operator requires both lexemes to appear in the same row’s tsv column.
EXPLAIN (ANALYZE, COSTS OFF)SELECT id, titleFROM filmsWHERE tsv @@ to_tsquery('simple', 'DRAMA & YUAN');
The query’s execution plan is shown below:
QUERY PLAN
-----------------------------------------------------------------------------------
Gather (actual time=382.078..384.864 rows=4.00 loops=1)
Workers Planned: 2
Workers Launched: 2
Buffers: shared hit=2517 read=78752
-> Parallel Seq Scan on films (actual time=306.088..377.774 rows=1.33 loops=3)
Filter: (tsv @@ '''drama'' & ''yuan'''::tsquery)
Rows Removed by Filter: 999999
Buffers: shared hit=2517 read=78752
Planning:
Buffers: shared hit=13
Planning Time: 0.375 ms
Execution Time: 384.884 ms
(12 rows)
Two workers and the main process participate in the parallel sequential scan, giving loops=3. Each participant returns an average of 1.33 matching rows, for a total of four matches. Total execution time is 384.884 ms.
Create a GIN index on the tsv column:
CREATE INDEX films_tsv_gin_idx ON films USING GIN (tsv);ANALYZE films;
With the GIN index in place, rerun the same search. The resulting execution plan is shown below:
QUERY PLAN
-------------------------------------------------------------------------------------------
Bitmap Heap Scan on films (actual time=0.695..0.729 rows=4.00 loops=1)
Recheck Cond: (tsv @@ '''drama'' & ''yuan'''::tsquery)
Heap Blocks: exact=3
Buffers: shared hit=20 read=20
-> Bitmap Index Scan on films_tsv_gin_idx (actual time=0.580..0.580 rows=4.00 loops=1)
Index Cond: (tsv @@ '''drama'' & ''yuan'''::tsquery)
Index Searches: 1
Buffers: shared hit=19 read=18
Planning:
Buffers: shared hit=28 read=5
Planning Time: 0.287 ms
Execution Time: 0.747 ms
(12 rows)
The Bitmap Index Scan uses the GIN index to locate the four matching rows. No rows are removed by rechecking because the index alone can determine whether both lexemes occur in the same row. In these runs, execution time fell from 384.884 ms to 0.747 ms.
In practice, finding matching rows is often only part of the task. We may also want to rank them by relevance and show the most relevant results first. For example:
SELECT category, actors_names, ts_rank_cd(tsv, to_tsquery('simple', 'DRAMA & YUAN')) AS rankFROM filmsWHERE tsv @@ to_tsquery('simple', 'DRAMA & YUAN')ORDER BY rank DESC;
This query uses ts_rank_cd() to rank the same four matching rows by cover density. Closer occurrences of drama and yuan contribute to a higher score in this example. Ranking changes the order of the matches, not their number.
Output is shown below:
category | actors_names | rank
----------+---------------------------------------------+-------------
drama | Yuan Vde, Rsn Syyhlq, Xmlp Qadocp | 0.1
drama | Eyseh Yuan, Nuhhkl Ecgzykh, Feducsc Tszpsjx | 0.05
drama | Syt Uaomwymv, Yuan Qawgy, Mxp Yjbzsru | 0.033333335
drama | Jgnaat Qbghc, Hjbxf Yuan, Oeeasz Saoys | 0.025
(4 rows)
The output shows that drama and yuan are adjacent in the first row, giving a rank of 0.1. In the second row, one word separates them, reducing the rank to 0.05. In the third and fourth rows, two and three words separate them, giving ranks of approximately 0.0333 and 0.025, respectively.
Next, we inspect the ranked search’s execution plan:
EXPLAIN (ANALYZE, COSTS OFF)SELECT category, actors_names, ts_rank_cd(tsv, to_tsquery('simple', 'DRAMA & YUAN')) AS rankFROM filmsWHERE tsv @@ to_tsquery('simple', 'DRAMA & YUAN')ORDER BY rank DESC;
The plan for the ranked search is:
QUERY PLAN
-------------------------------------------------------------------------------------------------
Sort (actual time=0.507..0.508 rows=4.00 loops=1)
Sort Key: (ts_rank_cd(tsv, '''drama'' & ''yuan'''::tsquery)) DESC
Sort Method: quicksort Memory: 25kB
Buffers: shared hit=40
-> Bitmap Heap Scan on films (actual time=0.480..0.499 rows=4.00 loops=1)
Recheck Cond: (tsv @@ '''drama'' & ''yuan'''::tsquery)
Heap Blocks: exact=3
Buffers: shared hit=40
-> Bitmap Index Scan on films_tsv_gin_idx (actual time=0.458..0.458 rows=4.00 loops=1)
Index Cond: (tsv @@ '''drama'' & ''yuan'''::tsquery)
Index Searches: 1
Buffers: shared hit=37
Planning:
Buffers: shared hit=1
Planning Time: 0.121 ms
Execution Time: 0.528 ms
(16 rows)
The GIN index finds the four matching rows. PostgreSQL fetches them from three heap blocks, calculates each row’s rank, and sorts the results from highest to lowest. This run took 0.528 ms.
GIN for Array Searches
The second typical use case is searching arrays with GIN. Using the existing films table, we convert the comma-separated actor names into an array, then use the @> operator to search for the exact array element Yuan Yao. This checks for a complete actor name rather than individual lexemes:
EXPLAIN (ANALYZE, COSTS OFF)SELECT id, titleFROM filmsWHERE string_to_array(actors_names, ', ') @> ARRAY['Yuan Yao'];
Output:
QUERY PLAN
---------------------------------------------------------------------------------------
Gather (actual time=1188.397..1190.621 rows=0.00 loops=1)
Workers Planned: 2
Workers Launched: 2
Buffers: shared hit=827 read=80729
-> Parallel Seq Scan on films (actual time=1183.392..1183.392 rows=0.00 loops=3)
Filter: (string_to_array(actors_names, ', '::text) @> '{"Yuan Yao"}'::text[])
Rows Removed by Filter: 1000000
Buffers: shared hit=827 read=80729
Planning:
Buffers: shared hit=123
Planning Time: 0.579 ms
Execution Time: 1190.818 ms
(12 rows)
Without an index on the array expression, PostgreSQL performs a parallel sequential scan, converts each row’s actor names into an array, and checks for Yuan Yao. None of the three million rows contains that exact array element. This run took 1190.818 ms, or about 1.19 seconds.
Now create a GIN index on the converted actor-name array:
CREATE INDEX films_actors_gin_idx ON films USING GIN (string_to_array(actors_names, ', '));ANALYZE films;
Rerun the same query to inspect the execution plan with the GIN index:
QUERY PLAN
----------------------------------------------------------------------------------------------
Bitmap Heap Scan on films (actual time=0.023..0.024 rows=0.00 loops=1)
Recheck Cond: (string_to_array(actors_names, ', '::text) @> '{"Yuan Yao"}'::text[])
Buffers: shared hit=5
-> Bitmap Index Scan on films_actors_gin_idx (actual time=0.019..0.019 rows=0.00 loops=1)
Index Cond: (string_to_array(actors_names, ', '::text) @> '{"Yuan Yao"}'::text[])
Index Searches: 1
Buffers: shared hit=5
Planning:
Buffers: shared hit=41 read=1
Planning Time: 0.288 ms
Execution Time: 0.040 ms
(11 rows)
With the GIN index in place, the execution time fell from 1190.818 ms to 0.040 ms. This example shows how the index can quickly establish that an exact actor name is absent.
GIN for JSONB Searches
The third typical use case is searching jsonb values with a GIN index. We start by creating a separate table from the existing films data, with one JSONB document for each film.
DROP TABLE IF EXISTS film_json;CREATE TABLE film_json ASSELECT id, jsonb_build_object( 'title', title, 'actors', string_to_array(actors_names, ', ') ) AS docFROM films;VACUUM (ANALYZE) film_json;
Next, we display one row to see how the films data is represented as JSONB:
postgres=# select * from film_json limit 1; id | doc----+---------------------------------------------------------------------------------- 1 | {"title": "xped", "actors": ["Nqetiw Fdgli", "Dbfjxr Uaqtmxw", "Pyikq Absvnaz"]}(1 row)
We can see that the doc column contains a JSONB object with the film’s title and an array of actors.
Next, we search for JSONB documents whose actors array contains the exact name Yuan Yao, using the JSONB containment operator @>:
EXPLAIN (ANALYZE, COSTS OFF)SELECT idFROM film_jsonWHERE doc @> '{"actors":["Yuan Yao"]}'::jsonb;
The execution plan is shown below:
QUERY PLAN
---------------------------------------------------------------------------------------
Gather (actual time=488.583..491.258 rows=0.00 loops=1)
Workers Planned: 2
Workers Launched: 2
Buffers: shared hit=2871 read=43266
-> Parallel Seq Scan on film_json (actual time=484.170..484.171 rows=0.00 loops=3)
Filter: (doc @> '{"actors": ["Yuan Yao"]}'::jsonb)
Rows Removed by Filter: 1000000
Buffers: shared hit=2871 read=43266
Planning Time: 0.095 ms
Execution Time: 491.276 ms
(10 rows)
Without a GIN index on doc, PostgreSQL performs a parallel sequential scan of all three million JSONB documents and finds no matches. This run took 491.276 ms, or about 0.49 seconds.
Now, we create a GIN index on the doc column using the jsonb_path_ops operator class, which supports this containment query:
CREATE INDEX film_json_gin_idx ON film_json USING GIN (doc jsonb_path_ops);ANALYZE film_json;
Rerun the same query to inspect the execution plan with the GIN index:
QUERY PLAN
-------------------------------------------------------------------------------------------
Bitmap Heap Scan on film_json (actual time=0.023..0.023 rows=0.00 loops=1)
Recheck Cond: (doc @> '{"actors": ["Yuan Yao"]}'::jsonb)
Buffers: shared hit=3 read=1
-> Bitmap Index Scan on film_json_gin_idx (actual time=0.017..0.018 rows=0.00 loops=1)
Index Cond: (doc @> '{"actors": ["Yuan Yao"]}'::jsonb)
Index Searches: 1
Buffers: shared hit=3 read=1
Planning:
Buffers: shared hit=17 read=3
Planning Time: 0.328 ms
Execution Time: 0.044 ms
(11 rows)
With the GIN index, the execution time fell from 491.276 ms to 0.044 ms.
Summary: Performance Comparison
The table below compares the execution times reported by EXPLAIN ANALYZE for the same queries with and without their corresponding GIN indexes. These speedups describe the recorded runs; cache state and I/O also affect the timings.
| Use case | Without GIN (ms) | With GIN (ms) | Approximate speedup |
|---|---|---|---|
Full-text search for drama and yuan | 384.884 | 0.747 | 515× |
Array containment of the exact name Yuan Yao | 1190.818 | 0.040 | 29,770× |
JSONB containment of Yuan Yao in actors | 491.276 | 0.044 | 11,165× |
These results demonstrate how GIN indexes can efficiently search for values within composite items. In the next article, we’ll explore the limitations of GIN indexes and see how an alternative index type, RUM, addresses these limitations.






Leave a Reply