Sobes.tech
Senior

What is the GIN index used for in PostgreSQL?

sobes.tech AI

Answer from AI

The GIN (Generalized Inverted Index) in PostgreSQL is used for efficient indexing and fast searching of complex data types such as arrays, JSONB, tsvector (text for full-text search), and others.

Main uses of GIN:

  • Searching by array elements (for example, finding rows where the array contains a specific value).
  • Full-text search using tsvector.
  • Indexing JSONB for quick key and value searches.

A GIN index stores, for each unique value, a list of references to the rows where this value appears, enabling fast search operations with operators like @>, ?, &&, and others.

Example of creating a GIN index for a JSONB field:

CREATE INDEX idx_data_gin ON my_table USING GIN (data jsonb_path_ops);

This significantly speeds up queries filtering by JSON content.