Video in progress
What kinds of queries need a GIN index, and how does it differ from a B-tree?
GIN is an "inverted index": for each element inside a value (an array element, a jsonb key, a word in text), it stores a list of rows. It suits "does it contain" queries, while a B-tree suits equality and ranges on the whole value.
📖 Answer
A B-tree stores a value as a single key, in sorted order. For queries like tags @> ARRAY['java'] or doc @> '{"type":"invoice"}' it can't help, because the search looks inside the value.
CREATE INDEX idx_product_attrs ON product USING gin (attrs jsonb_path_ops);
SELECT * FROM product WHERE attrs @> '{"color": "red"}';
CREATE INDEX idx_article_fts ON article
USING gin (to_tsvector('simple', title || ' ' || body));
SELECT * FROM article
WHERE to_tsvector('simple', title || ' ' || body) @@ plainto_tsquery('simple', 'kafka');
jsonb_path_ops supports only @>, but it's smaller and faster. The default jsonb_ops also supports the key operators like ? and ?|.
The cost is on writes: one row maps to dozens of index entries. That's why GIN works with fastupdate by default: new entries first go to a pending list, then get moved into the main index by vacuum or when the list fills up. Sometimes that's why a single insert suddenly gets slow: that's when the pending list is being flushed.
For LIKE '%abc%' you use gin_trgm_ops with the pg_trgm extension.
Sign up to mark studied questions and save your progress.