GIN indexes are powerful tools for searching within composite values in PostgreSQL, but they have limitations in real-world applications. RUM builds on GIN’s inverted-index design to overcome some of these limitations, particularly in full-text search. This post compares GIN and RUM through practical experiments to help you decide which is better suited to your workload.

This is the second post in a three-part series on PostgreSQL inverted indexes:

  1. Three Typical GIN Index Use Cases in PostgreSQL
  2. How RUM Overcomes GIN’s Limitations in PostgreSQL Full-Text Search
  3. The Cost of Maintaining GIN and RUM Indexes in PostgreSQL

The examples in this post use the same films table as the first post.

The index names share a playful connection: GIN stands for Generalized Inverted Index and is also the name of a popular spirit. RUM continues the drinks theme with another spirit’s name. Despite their lighthearted names, the two index methods have meaningful technical differences.

RUM Stores More to Do More

For full-text search, both GIN and RUM store lexemes and the TIDs of tuples containing them. RUM also stores lexeme positions alongside each TID, which is particularly useful for phrase searches and ranking results by the proximity of matching lexemes

The following diagram, from the previous post, conceptually illustrates the entries in the GIN index for tsvector values.

As shown in the diagram below, a RUM index stores lexeme positions alongside their corresponding TIDs.

RUM can also attach extra column values to index entries to support additional filtering and ordering. We’ll see examples below.

Although the extra information extends RUM’s capabilities, storing and maintaining it generally increases index size, build time, and update costs compared with GIN.

Using Lexeme Positions to Measure Distance

For full-text search, RUM provides the <=> operator between a tsvector and a tsquery to calculate a relevance distance. Smaller values indicate better matches. This score uses lexeme positions; it is not a literal word count or the absolute difference between two numbers.

Enable the extension before using this operator. RUM must already be installed on the PostgreSQL server. Start with the GIN index, before creating the RUM index:

CREATE EXTENSION IF NOT EXISTS rum;
CREATE INDEX films_tsv_gin_idx ON films USING GIN (tsv);
ANALYZE films;

The following query finds films whose text contains both war and yao, then returns the five with the smallest relevance distances:

SELECT category,
actors_names,
tsv <=> to_tsquery('simple', 'WAR & YAO') AS distance
FROM films
WHERE tsv @@ to_tsquery('simple', 'WAR & YAO')
ORDER BY distance
LIMIT 5;

Example output:

 category |               actors_names               | distance
----------+------------------------------------------+-----------
 war      | Yao Qsncolw, Swteoukb Yzetk, Jcxih Npc   |   8.22467
 war      | Xatxpu Yao, Upuvak Kdfpihb, Mhbymsor Fzw |  16.44934
 war      | Wvb Hnpv, Yao Bgkkw, Vxx Yfdyvns         | 24.674011
 war      | Ofqzwd Xekxv, Jtxl Yao, Vrkodt Xbajly    |  32.89868
 war      | Pxq Kwyqrw, Leyc Nwy, Yao Roqkwzd        | 41.123352
(5 rows)

The generated tsv combines the title, category, and actor names in that order. In these five rows, the titles contain neither war nor yao, and the category is war. In the first row, war and yao are adjacent. Each subsequent row places one more word between them, increasing the distance from approximately 8.22 to 16.45, 24.67, 32.90, and 41.12. These values are relevance scores, not literal word counts.

Inspect the query’s execution plan:

EXPLAIN (ANALYZE, COSTS OFF, BUFFERS)
SELECT category,
actors_names,
tsv <=> to_tsquery('simple', 'WAR & YAO') AS distance
FROM films
WHERE tsv @@ to_tsquery('simple', 'WAR & YAO')
ORDER BY distance
LIMIT 5;

The GIN execution plan is:

 Limit (actual time=3.137..3.139 rows=5.00 loops=1)
   Buffers: shared hit=155
   ->  Sort (actual time=3.136..3.137 rows=5.00 loops=1)
         Sort Key: ((tsv <=> '''war'' & ''yao'''::tsquery))
         Sort Method: top-N heapsort  Memory: 25kB
         Buffers: shared hit=155
         ->  Bitmap Heap Scan on films (actual time=3.085..3.120 rows=38.00 loops=1)
               Recheck Cond: (tsv @@ '''war'' & ''yao'''::tsquery)
               Heap Blocks: exact=2
               Buffers: shared hit=155
               ->  Bitmap Index Scan on films_tsv_gin_idx (actual time=3.068..3.068 rows=38.00 loops=1)
                     Index Cond: (tsv @@ '''war'' & ''yao'''::tsquery)
                     Index Searches: 1
                     Buffers: shared hit=153
 Planning:
   Buffers: shared hit=1
 Planning Time: 0.112 ms
 Execution Time: 3.159 ms

The Bitmap Index Scan on the GIN index identifies all 38 matches. The Bitmap Heap Scan fetches their vectors from two heap blocks, and PostgreSQL calculates a distance for each match. The Sort node uses a top-N heapsort to select the five best matches. GIN supports the @@ filter, but it cannot supply results in <=> distance order. The <=> operator comes from the RUM extension even though this plan uses a GIN index.

Create a RUM index:


CREATE INDEX films_tsv_rum_idx
    ON films USING rum (tsv rum_tsvector_ops);

ANALYZE films;



Rerun the same EXPLAIN query. With both indexes available, PostgreSQL chooses the RUM index in this run:

 Limit (actual time=0.968..0.976 rows=5.00 loops=1)
   Buffers: shared hit=233, temp read=18 written=18
   ->  Index Scan using films_tsv_rum_idx on films (actual time=0.968..0.974 rows=5.00 loops=1)
         Index Cond: (tsv @@ '''war'' & ''yao'''::tsquery)
         Order By: (tsv <=> '''war'' & ''yao'''::tsquery)
         Index Searches: 0
         Buffers: shared hit=233, temp read=18 written=18
 Planning:
   Buffers: shared hit=36
 Planning Time: 0.256 ms
 Execution Time: 1.061 ms

By storing lexeme positions in its postings, RUM can calculate relevance distances within the index and supply results in relevance order, avoiding a separate Sort. Execution time falls from 3.159 ms with GIN to 1.061 ms with RUM, making RUM approximately 2.98 times as fast in this run.

Searching for an Exact Phrase

Phrase search is useful for names, titles, and other expressions where the words need to stay together. It filters out results that contain the individual words in unrelated places or in the wrong order.

For example, a word search for Taylor & Swift requires both lexemes to appear anywhere in the text, in either order. A phrase search for Taylor <-> Swift requires swift to appear immediately after taylor. Within a tsquery, PostgreSQL’s built-in phrase-search operator <-> expresses this positional requirement:

TextWord search: Taylor & SwiftPhrase search: Taylor <-> Swift
Taylor SwiftMatchesMatches
Taylor Alison SwiftMatchesDoes not match
Swift TaylorMatchesDoes not match

With the simple text search configuration, all three examples match the word search. Only Taylor Swift matches the phrase search: Taylor Alison Swift has a word in between, and Swift Taylor reverses the required order.

Now apply the same idea to the films table: search for war immediately followed by yao. First, check the available indexes:

SELECT indexname, indexdef
FROM pg_indexes
WHERE schemaname = 'public'
AND tablename = 'films';

Both GIN and RUM are available on the search vector, alongside the primary-key index:

     indexname     |                            indexdef
-------------------+-----------------------------------------------------------------
 films_pkey        | CREATE UNIQUE INDEX films_pkey ON public.films USING btree (id)
 films_tsv_gin_idx | CREATE INDEX films_tsv_gin_idx ON public.films USING gin (tsv)
 films_tsv_rum_idx | CREATE INDEX films_tsv_rum_idx ON public.films USING rum (tsv)
(3 rows)

Run the phrase search and inspect its execution plan:

EXPLAIN (ANALYZE, COSTS OFF, BUFFERS)
SELECT id, category, actors_names
FROM films
WHERE tsv @@ to_tsquery('simple', 'war <-> yao');

With both indexes available, PostgreSQL chooses RUM:

 Bitmap Heap Scan on films (actual time=193.630..193.631 rows=1.00 loops=1)
   Recheck Cond: (tsv @@ '''war'' <-> ''yao'''::tsquery)
   Heap Blocks: exact=1
   Buffers: shared hit=351
   ->  Bitmap Index Scan on films_tsv_rum_idx (actual time=193.611..193.611 rows=1.00 loops=1)
         Index Cond: (tsv @@ '''war'' <-> ''yao'''::tsquery)
         Index Searches: 0
         Buffers: shared hit=350
 Planning:
   Buffers: shared hit=2
 Planning Time: 0.106 ms
 Execution Time: 194.100 ms

RUM uses the lexeme positions stored in its index to check the phrase and returns just one candidate. PostgreSQL visits one heap block to retrieve the matching row. Yet the query takes 194.100 ms, almost all of it spent inside the RUM index scan.

Now drop the RUM index and run exactly the same query again:

DROP INDEX films_tsv_rum_idx;
EXPLAIN (ANALYZE, COSTS OFF, BUFFERS)
SELECT id, category, actors_names
FROM films
WHERE tsv @@ to_tsquery('simple', 'war <-> yao');

PostgreSQL now chooses GIN:

 Bitmap Heap Scan on films (actual time=3.296..3.366 rows=1.00 loops=1)
   Recheck Cond: (tsv @@ '''war'' <-> ''yao'''::tsquery)
   Rows Removed by Index Recheck: 37
   Heap Blocks: exact=2
   Buffers: shared hit=75 read=80
   ->  Bitmap Index Scan on films_tsv_gin_idx (actual time=3.268..3.268 rows=38.00 loops=1)
         Index Cond: (tsv @@ '''war'' <-> ''yao'''::tsquery)
         Index Searches: 1
         Buffers: shared hit=74 read=79
 Planning:
   Buffers: shared hit=6 dirtied=1
 Planning Time: 0.135 ms
 Execution Time: 3.384 ms

With RUM removed, GIN finds 38 candidates containing both words. PostgreSQL visits the table to read their search vectors and check the positions. Thirty-seven rows fail that check, leaving the same single phrase match. This run takes 3.384 ms, making GIN approximately 57 times as fast as RUM.

RUM is slower here because its index scan takes approximately 193.6 ms, compared with 3.3 ms for GIN. Although RUM checks lexeme positions within the index, GIN needs to fetch only two heap blocks to recheck all 38 candidates, making that work inexpensive. RUM’s extra index-processing cost outweighs the small saving in heap access. If a query produces many more candidates spread across many heap blocks, especially pages that are not cached, checking positions within the RUM index could offer a greater advantage. These plans locate the slowdown in the RUM index scan but do not identify the exact internal operation responsible.

Ordering Search Results by an Attached Column

The next experiment orders search results by another column. We search for war and return ten films ordered by their release-date distance from today. RUM can support this ordering by attaching release_date values to the search-vector postings.

First, remove the positional RUM index if it is still present. It was already dropped in the preceding experiment:

DROP INDEX IF EXISTS films_tsv_rum_idx;

The following query finds films containing war and returns ten rows ordered by their release-date distance from the start of today. For timestamps on or before that reference point, RUM’s <=| operator returns the elapsed time in seconds; timestamps after the reference point receive an infinite distance. Thus, when at least ten matches were released on or before that point, this query returns the ten most recent of those films.

EXPLAIN (ANALYZE, COSTS OFF, BUFFERS)
SELECT id,
release_date,
release_date <=| CURRENT_DATE::timestamp AS release_date_distance
FROM films
WHERE tsv @@ to_tsquery('simple', 'war')
ORDER BY release_date_distance
LIMIT 10;

With GIN, PostgreSQL produces this plan:

 Limit (actual time=818.301..818.305 rows=10.00 loops=1)
   Buffers: shared hit=1 read=81337 written=4
   ->  Sort (actual time=818.300..818.301 rows=10.00 loops=1)
         Sort Key: ((release_date <=| (CURRENT_DATE)::timestamp without time zone))
         Sort Method: top-N heapsort  Memory: 26kB
         Buffers: shared hit=1 read=81337 written=4
         ->  Bitmap Heap Scan on films (actual time=108.582..701.933 rows=599258.00 loops=1)
               Recheck Cond: (tsv @@ '''war'''::tsquery)
               Rows Removed by Index Recheck: 975391
               Heap Blocks: exact=48218 lossy=33026
               Buffers: shared hit=1 read=81337 written=4
               ->  Bitmap Index Scan on films_tsv_gin_idx (actual time=97.914..97.914 rows=599258.00 loops=1)
                     Index Cond: (tsv @@ '''war'''::tsquery)
                     Index Searches: 1
                     Buffers: shared hit=1 read=93
 Planning:
   Buffers: shared hit=3 read=3 dirtied=1
 Planning Time: 0.192 ms
 Execution Time: 818.333 ms

GIN identifies 599,258 matching rows. PostgreSQL then fetches those rows from the table, calculates their release-date distances, and uses a top-N heapsort to select the ten smallest distances. Although the query returns only ten rows, PostgreSQL must process all matches first. This run takes 818.333 ms.

Now create a RUM index that attaches release_date to the tsv postings:

CREATE INDEX films_tsv_rum_sort_idx
ON films USING rum (tsv rum_tsvector_addon_ops, release_date)
WITH (attach = 'release_date', to = 'tsv');
ANALYZE films;

We use the addon operator class for the search vector. The attach and to options tell RUM to store release_date values alongside the tsv postings so it can use them for ordering.

Rerun the same query. PostgreSQL now chooses the attached-column RUM index:

 Limit (actual time=552.934..552.999 rows=10.00 loops=1)
   Buffers: shared hit=847 read=3, temp read=6709 written=7688
   ->  Index Scan using films_tsv_rum_sort_idx on films (actual time=552.932..552.996 rows=10.00 loops=1)
         Index Cond: (tsv @@ '''war'''::tsquery)
         Order By: (release_date <=| (CURRENT_DATE)::timestamp without time zone)
         Index Searches: 0
         Buffers: shared hit=847 read=3, temp read=6709 written=7688
 Planning:
   Buffers: shared hit=45
 Planning Time: 0.285 ms
 Execution Time: 555.495 ms

The Order By inside the index scan shows that RUM supplies rows in date-distance order. There is no separate Sort node, and the index scan returns ten rows to Limit, avoiding GIN’s need to fetch every matching row from the heap to calculate its distance. PostgreSQL still accesses the heap for tuple visibility and the selected columns.

Execution time falls from 818.333 ms to 555.495 ms, making RUM approximately 1.47 times as fast in this run.

What the Experiments Show

The three experiments illustrate where RUM reduces query work and why that does not always lead to faster execution:

  • RUM stores lexeme positions in its index, so PostgreSQL does not need to fetch search vectors from the table to calculate relevance distances or verify phrase positions. We saw this in both the ranking and phrase experiments. PostgreSQL can still visit the table to retrieve selected columns and check row visibility.
  • For the ordered queries with a limit, GIN identifies all the matches, then PostgreSQL reads their values and sorts them to select the top results. RUM supplies rows in the requested distance order and stops returning rows once the limit is satisfied. This removes the separate sort, although RUM may still perform substantial work inside the index before producing those rows.
  • RUM can also order by an attached column. The release-date experiment shows that this capability extends beyond text relevance: attaching dates lets one index support both the text filter and date-distance ordering.
  • Doing more inside the index does not always make a query faster. RUM was approximately 2.98 times as fast in the relevance experiment and 1.47 times as fast in the attached-column experiment. In the phrase experiment, however, its index scan cost much more than the table rechecks it saved, and GIN finished approximately 57 times as fast.
  • The dataset limits how much of RUM’s advantage these experiments reveal. In the selective queries, GIN accesses only a few table blocks, making its extra table work inexpensive. With a larger dataset and more candidates spread across uncached table blocks, those visits could become much more costly. RUM’s ability to perform ranking and positional checks within the index could then offer a greater advantage.

Considerations When Choosing Between GIN and RUM

When you are choosing between GIN and RUM, consider your query patterns and the tradeoffs below:

  • GIN is a strong starting point for containment queries, JSONB and array searches, and simple full-text matching. It is built into PostgreSQL, has no extension dependency, and generally uses less space and requires less build and maintenance work than RUM.
  • Consider RUM when ranking or ordering a large set of matches is a bottleneck. Its ability to supply results in the requested order can reduce table access and remove a separate sort.
  • To use the ordering features of RUM, write the query with an ordering operator supported by the chosen operator class. For example, the relevance query uses ORDER BY tsv <=> to_tsquery('simple', 'WAR & YAO'), while the attached-column query orders by release_date <=| CURRENT_DATE::timestamp. Adding a RUM index does not automatically make an arbitrary ranking expression use index ordering.
  • Balance any query speedup against storage, build time, and update costs. RUM stores additional information, which generally makes its indexes larger and adds maintenance work. These experiments measure query execution, not write overhead. Test representative queries and data under realistic cache conditions to determine whether the read benefits justify those costs for your application.

In this post, we explored how RUM overcomes some of GIN’s limitations in full-text search and how to choose between them based on your application’s query patterns. How PostgreSQL maintains these indexes is another important factor in that decision. We’ll explore it in the next post.

2 responses to “How RUM Overcomes GIN’s Limitations in PostgreSQL Full-Text Search”

  1. The Cost of Maintaining GIN and RUM Indexes in PostgreSQL – Yuan Yao, An Oracle ACE's Blog avatar

    […] How RUM Overcomes GIN’s Limitations in PostgreSQL Full-Text Search […]

    Like

  2. Three Typical GIN Index Use Cases in PostgreSQL – Yuan Yao, An Oracle ACE's Blog avatar

    […] How RUM Overcomes GIN’s Limitations in PostgreSQL Full-Text Search […]

    Like

Leave a Reply

I’m Yuan

Welcome to the blog of a database performance maven. Feel free to contact me to share and discuss database knowledge.

My Oracle Book

My 26 Oracle Certifications

A screenshot from certview.oracle.com

My MySQL Book

MySQL 8.0 Operations and Optimization

Let’s connect