AboutBlogContact
DatabasesJuly 14, 2006 2 min read 26

PostgreSQL: GIN and GiST Indices (2006)

AunimedaAunimeda

PostgreSQL: GIN and GiST Indices

PostgreSQL 8.2 is here, and it's making other databases look like toys. While MySQL is still struggling with basic subqueries, Postgres is giving us Generalized Search Trees (GiST) and Generalized Inverted Indices (GIN).

GiST: The "Anything" Index

GiST is a template that allows you to build indices for complex data types like points, polygons, or even custom IP ranges.

-- Using GiST for geometric search
CREATE TABLE locations (
    id serial PRIMARY KEY,
    geom point
);

CREATE INDEX locations_geom_idx ON locations USING gist (geom);

-- Find points within a circle
SELECT * FROM locations WHERE geom <@ circle '<(0,0), 10>';

GIN: The Power of Inversion

GIN is designed for data where a single column contains multiple values, like arrays or full-text search documents. Unlike a B-Tree, which points to a row, GIN points to elements within the row.

-- Full-text search with GIN
CREATE TABLE articles (
    id serial PRIMARY KEY,
    body text,
    body_vector tsvector
);

-- Update the vector for search
UPDATE articles SET body_vector = to_tsvector('english', body);

-- Index the vector
CREATE INDEX articles_search_idx ON articles USING gin (body_vector);

-- Lightning fast search
SELECT * FROM articles 
WHERE body_vector @@ to_tsquery('postgres & indexing');

If you're doing full-text search with LIKE '%term%', stop. You're killing your server. GIN indices make your searches O(log N) instead of O(N).

Read Also

PostgreSQL 7.3: Utilizing Schemas for Better Database Isolation (2003)aunimeda
Databases

PostgreSQL 7.3: Utilizing Schemas for Better Database Isolation (2003)

The release of PostgreSQL 7.3 brings a feature we've been waiting for: Schemas. No more prefixing every table with 'app1_'. Let's organize our data properly.

PostgreSQL 1.0: The POSTGRES95 Transitionaunimeda
Databases

PostgreSQL 1.0: The POSTGRES95 Transition

Postgres is back, and it's finally speaking SQL. POSTGRES95 marks the transition from an academic project at Berkeley to a real-world open-source database.

SQL-92: The Day Databases Finally Started Speaking the Same Languageaunimeda
Databases

SQL-92: The Day Databases Finally Started Speaking the Same Language

The SQL-92 standard is finally here. No more vendor-specific joins and cryptic syntax. Well, mostly.

Need IT development for your business?

We build websites, mobile apps and AI solutions. Free consultation.

Get Consultation All articles