What types of indexes exist in PostgreSQL?
sobes.tech AI
Answer from AI
The following are the main types of indexes:
-
B-tree (B-Tree) - the most common type, suitable for most typical queries (equality, comparison, range). Based on a balanced tree.
-
Hash - used for equality checks (=). Faster than B-tree for such queries but does not support comparisons and ranges. Stores a hash value of the key and a pointer to the string.
-
GiST (Generalized Search Tree) - a generalized search tree structure that allows building various indexes for complex data types (geometric, textual with full-text search). Based on a balanced tree.
-
SP-GiST (Space-Partitioned Generalized Search Tree) - a specialized version of GiST for data that can be divided by space (e.g., points, rectangles). Examples: k-d trees, quadtrees.
-
GIN (Generalized Inverted Index) - a generalized inverted index mainly for searching elements within composite values (e.g., arrays, JSONB). Often used for full-text search.
-
BRIN (Block Range INdex) - a block range index. Suitable for very large tables with naturally ordered data (e.g., by time). Indexes the range of values in physical disk blocks.
-
Bloom (Bloom filter) - not a traditional index, but a probabilistic data structure for quickly checking the absence of an element. Used to speed up selection from very large tables when exact matching is not required or as an additional filter before scanning the main index.
Examples of usage:
- B-tree: Index on numeric fields, dates, strings for range searches (
WHERE amount > 100). - Hash: Rarely used directly, as B-tree is usually faster for most tasks.
- GiST: Geospatial indexes (
gist(location)), indexes for full-text search (to_tsvector). - SP-GiST: Indexes for two-dimensional data (
spgist(point)). - GIN: Indexes for arrays (
gin(tags)), JSONB (gin(data)), full-text search. - BRIN: Index on
timestampfield in log tables where data is ordered by time. - Bloom: Index on a set of columns (
bloom(col1, col2, col3)) for quick filtering of rows where the combination of values is definitely not present.
The choice of index type depends on the column data type and the kind of queries that need to be optimized.