Introduction
A GiST index helps speed up searches on complex data like shapes or text by organizing data smartly.
Jump into concepts and practice - no test required
A GiST index helps speed up searches on complex data like shapes or text by organizing data smartly.
CREATE INDEX index_name ON table_name USING gist (column_name);
CREATE INDEX location_gist_idx ON places USING gist (location);
CREATE INDEX textsearch_gist_idx ON documents USING gist (to_tsvector('english', content));
This example creates a table with polygon areas, adds a GiST index on the area column, and queries parks overlapping a specific polygon.
CREATE TABLE parks (id SERIAL PRIMARY KEY, name TEXT, area POLYGON); INSERT INTO parks (name, area) VALUES ('Central Park', '((0,0),(0,10),(10,10),(10,0),(0,0))'), ('Riverside Park', '((5,5),(5,15),(15,15),(15,5),(5,5))'); CREATE INDEX parks_area_gist_idx ON parks USING gist (area); -- Find parks overlapping a given area SELECT name FROM parks WHERE area && '((7,7),(7,12),(12,12),(12,7),(7,7))'::polygon;
GiST indexes are great for range and similarity searches but may be slower to update than regular indexes.
Use GiST indexes when your queries involve geometric operators like overlaps (&&) or full-text search functions.
GiST indexes speed up searches on complex data like shapes and text.
They work well with geometric types and full-text search.
Create them using CREATE INDEX ... USING gist (column).
places_location_gist on a column named location in table places?shapes with a box column of type box, and a GiST index created on box, what will the query below return?SELECT * FROM shapes WHERE box && '(1,1),(4,4)'::box;&& means "overlaps" for geometric types.@@ operator to use the index.@@ operator, which prevents index usage. GiST indexes do not support text search is false--GiST supports text search. Options A and D are possible but less directly related to index usage.documents with a column content of type tsvector for fast full-text search. Which of the following statements correctly creates the index and allows efficient search for the phrase 'open source'?tsvector column directly, as in CREATE INDEX content_gist_idx ON documents USING gist (content);
SELECT * FROM documents WHERE content @@ to_tsquery('open & source');content @@ to_tsquery('open & source'), which is the correct way to search for both words with AND logic. CREATE INDEX content_gist_idx ON documents USING gist (content);
SELECT * FROM documents WHERE content LIKE '%open source%'; uses LIKE, which does not use the index. CREATE INDEX content_gist_idx ON documents USING btree (content);
SELECT * FROM documents WHERE content @@ to_tsquery('open & source'); uses btree index, which is not suitable for tsvector. CREATE INDEX content_gist_idx ON documents USING gist (content);
SELECT * FROM documents WHERE to_tsvector(content) @@ to_tsquery('open & source'); applies to_tsvector on the column again, which is unnecessary and inefficient.