AI Hints
Home›PostgreSQL Tutorial›GIN, BRIN and Index Mistakes
PostgreSQL · Lesson 55 of 120

GIN Indexes

For arrays, JSON and text.

⏱ 2 min read▶ Video at 48:33🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

AB tree indexes whole values. But arrays and JSONB hold many values each. AGIN index lists every element, and which rows contain it, like an inverted index.

  • Many values per row
  • Index each element
  • GIN

GIN on JSONB

We copy customers many times to make a bigger table, then add a GIN index on prefs. The containment query can now use it. Run it. A bitmap index scan on the GIN index.

query.sqlsql
CREATE TABLE fans AS
SELECT c.* FROM customers c, generate_series(1, 200);
CREATE INDEX fans_prefs ON fans USING gin (prefs);
ANALYZE fans;

EXPLAIN (COSTS OFF)
SELECT count(*) FROM fans
WHERE prefs @> '{"format": "audiobook"}';
Output
SELECT 100000
CREATE INDEX
ANALYZE
                              QUERY PLAN
-----------------------------------------------------------------------
 Aggregate
   ->  Bitmap Heap Scan on fans
         Recheck Cond: (prefs @> '{"format": "audiobook"}'::jsonb)
         ->  Bitmap Index Scan on fans_prefs
               Index Cond: (prefs @> '{"format": "audiobook"}'::jsonb)
(5 rows)

GIN uses

GIN speeds up array operators like contains and overlap. It speeds up JSONB containment and key checks. And it powers full text search. It's slower to update than a B tree, so use it where you search a lot.

keyvalue
Arrays@> && <@
JSONB@> ? ?|
Full-texttsvector
Trade-offslower writes

Summary

GIN indexes index every element, for fast array, JSONB and text searches. Next, the tiny BRIN index.

Key takeaways
  • GIN
  • @>
  • Elements
Next up: BRIN Indexes — tiny indexes for huge tables