Consider a PostgreSQL table shapes with a box column storing geometric boxes. A GiST index is created on this column. What will be the output of the following query?
SELECT count(*) FROM shapes WHERE box && '((1,1),(5,5))'::box;
Assume the table has these rows:
- box '((0,0),(2,2))'
- box '((3,3),(6,6))'
- box '((6,6),(8,8))'
CREATE TABLE shapes (id SERIAL PRIMARY KEY, box box); INSERT INTO shapes (box) VALUES ('((0,0),(2,2))'), ('((3,3),(6,6))'), ('((6,6),(8,8))'); CREATE INDEX shapes_box_gist_idx ON shapes USING gist(box); SELECT count(*) FROM shapes WHERE box && '((1,1),(5,5))'::box;
The && operator checks if two boxes overlap.
The boxes '((0,0),(2,2))' and '((3,3),(6,6))' overlap with '((1,1),(5,5))'. The third box does not overlap. So the count is 2.
Why is a GiST index useful for full-text search in PostgreSQL?
Think about what GiST indexes can do with special data types.
GiST indexes support indexing of complex data types such as tsvector, which is used for full-text search, enabling fast search operations.
Which of the following SQL statements correctly creates a GiST index on a tsvector column named document_vector in a table articles?
GiST indexes require the gist keyword and do not use operator classes like text_pattern_ops for tsvector.
Option A correctly creates a GiST index on the tsvector column. Option A uses btree which is not suitable. Option A incorrectly uses operator class. Option A uses hash which is not supported for tsvector.
You have a table locations with a point column storing coordinates. You want to find all points within a rectangle quickly. Which query will best use a GiST index on the point column?
Look for the operator that checks if a point is inside a box.
The <@ operator checks if a point is contained within a box and can use a GiST index efficiently. The && operator is for box overlap, not point containment.
A developer created a GiST index on a tsvector column content_vector in table documents. However, queries using to_tsvector('english', content) in the WHERE clause are slow and do not use the index. Why?
Check if the query expression matches the indexed column.
The index is on the content_vector column, but the query uses to_tsvector('english', content) which is a function call and not the indexed column itself. To use the index, the query must filter on the indexed column or create an expression index matching the query.