0%
PostgreSQL Deep Dive: MVCC, Vacuum, Plans, and Replication
Architecture and Storage
MVCC and Vacuum
Concurrency and Schema
GIN, GiST and BRIN
B-trees handle scalar values that can be sorted: numbers, text, timestamps. Many modern workloads need something else: searching inside arrays and JSON documents, matching words in text, finding overlapping time ranges or nearby points, or indexing a ten terabyte append only table cheaply. PostgreSQL has an extensible index framework with several access methods designed for these cases. This section explains the framework, why B-trees cannot serve these queries, and gives a first map of which index type fits which problem.
The access method interface
An index access method in Postgres is a set of functions implementing build, insert, scan and vacuum for a particular index structure, registered in pg_am. The built in methods are btree, hash, gist, spgist, gin and brin, and extensions can add more, such as bloom or vector indexes like those from pgvector. The planner does not know the internals of any of them; it asks each one about cost and capability through the interface, which is how a new index type can be added without changing the planner.
Operator classes connect types to indexes
Which queries an index can serve is decided by its operator class, which tells the access method how to handle a data type and which operators it supports. A B-tree operator class for integers supports less than, equals and greater than. A GIN operator class for jsonb supports containment and key existence. A GiST operator class for ranges supports overlap and containment. A query can use an index only if its WHERE clause uses an operator from the index operator class with the indexed column on one side, so knowing the operators is essential.
What B-trees cannot do
A B-tree orders whole values, so it answers questions about where a value falls in that order. It cannot answer whether an array contains an element, whether a document has a key, whether a text contains a word or a substring, whether two ranges overlap, or which points are nearest to a location, because none of these questions map to a contiguous range of sorted values. Each of them needs a structure that indexes parts of values, or bounding regions, rather than whole values in order.
Inverted indexes for composite values
When values are made of many elements, such as arrays of tags, words in a document or keys in a JSON object, the natural index is inverted: for each element, a list of the rows that contain it. Searching for rows containing an element becomes a lookup of that element list, and searching for several elements intersects or unions lists. GIN, the generalized inverted index, implements this for any type that can be decomposed into elements, with operator classes for arrays, jsonb, full text search and trigrams.
Search trees for spatial and range data
Geometric shapes, ranges and other values that can overlap do not sort into a line, but they can be grouped by bounding regions. A tree whose internal nodes store a region covering everything below them can answer overlap, containment and nearest neighbor questions by descending only into nodes whose regions could match. GiST, the generalized search tree, is a framework for such balanced trees, used for ranges, geometry, PostGIS shapes and exclusion constraints. SP-GiST supports unbalanced space partitioning trees like quadtrees and radix tries.
Summaries for very large tables
For huge tables where data is physically ordered by some column, such as an event table ordered by time, a full index is expensive while a tiny summary is enough. BRIN, the block range index, stores the minimum and maximum value of a column for each range of pages, so a query for a time window can skip ranges whose summaries do not overlap it. A BRIN index on a terabyte table can be a few megabytes, at the price of reading whole page ranges rather than individual rows.
Hash indexes
Hash indexes support only equality and store a hash of each value rather than the value itself, which makes them compact for long keys such as URLs. They have been crash safe and WAL logged since version 10. In practice a B-tree is usually just as fast for equality and also supports ranges, ordering and uniqueness, so hash indexes are a niche choice for equality lookups on wide values where index size matters. They cannot be unique or multicolumn.
Extensions add more
The extension ecosystem fills gaps. pg_trgm provides trigram operator classes for GIN and GiST, enabling fast LIKE and similarity search. btree_gin and btree_gist provide operator classes for scalar types so they can be combined with other columns in GIN or GiST indexes, for example in exclusion constraints. PostGIS builds on GiST and SP-GiST for spatial data. pgvector adds IVFFlat and HNSW access methods for vector similarity. bloom provides a signature index for many columns with equality.
Costs common to all of them
Every index type adds write cost on insert and update, vacuum work and disk space, and each has its own trade offs between build time, size, write speed and query precision. GIN indexes are slow to update but fast to search. GiST indexes are lossy and need rechecks. BRIN indexes are tiny and cheap but only help on well correlated data. The rest of this lesson goes through each in enough depth to choose confidently and to recognize when an index is the wrong type for its queries.
Strategies and support functions
Inside an operator class, each supported operator is assigned a strategy number, and the access method calls support functions to do its work. For a B-tree, the support function is a comparison returning less, equal or greater. For GIN, support functions extract keys from a value and from a query and decide whether a row matches given which keys it has. For GiST, they compute unions of keys, penalties for adding a key to a subtree and how to split a full page. Writing a new operator class means implementing these functions, which is how extensions teach indexes about new types.
Listing what an index supports
The catalogs answer which operators an index can serve. Joining pg_opclass, pg_amop and pg_operator for an operator class lists its operators, and psql commands such as dAo and dAc show operator families and classes by access method. Checking this before creating an index, or when an index is mysteriously unused, often reveals that the query uses an operator the index does not support, such as the question mark key existence operator against a jsonb_path_ops index.
Indexes on expressions of any type
Every access method supports expression indexes, not only B-trees. A GIN index on to_tsvector of a title and body, a GiST index on a range built from two columns, or a BRIN index on an expression of a timestamp all work, as long as the expression is immutable and the query uses the same expression. This lets tables keep their natural columns while indexes serve specialized queries, though a generated column is often clearer and gives the planner statistics on the value.
Planner costing for specialized indexes
The planner estimates selectivity for operators using statistics and operator specific estimation functions. For containment on arrays and jsonb, it uses most common element statistics gathered by ANALYZE; for ranges, it uses range length and bound histograms; for full text, lexeme frequencies. When these estimates are poor, the planner may skip a GIN or GiST index that would help, or use one that does not. Increasing the statistics target on the column often improves the estimate.
Bloom indexes
The bloom extension builds a signature index where each row gets a small bit signature derived from several columns. A query with equality conditions on any subset of those columns checks signatures and rechecks matches. It suits tables queried by arbitrary combinations of many columns, where creating a B-tree for every combination is impractical, though it is lossy and supports only equality.
Indexes serve queries through operator classes. B-trees order whole values; GIN inverts composite values into elements; GiST and SP-GiST group values by regions for overlap and distance; BRIN summarizes page ranges of naturally ordered data. Extensions like pg_trgm and btree_gist fill gaps.