AI Hints
Home›PostgreSQL Tutorial›Fast Search, Fuzzy Search, Practice
PostgreSQL · Lesson 61 of 120

A Search Column and Index

Fast search.

⏱ 2 min read▶ Video at 54:35🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

Calling to tsvector on every row, on every search, is slow. Instead, store the tsvector in a generated column, and put a GIN index on it.

  • Computed every search?
  • Store it
  • Index it

Stored tsvector plus GIN

The search column is generated from the title and author, with the title weighted higher. AGIN index makes it fast. Then we search it directly. Run it. Matching books, best first.

query.sqlsql
ALTER TABLE books ADD COLUMN search tsvector GENERATED ALWAYS AS (
  setweight(to_tsvector('english', title), 'A') ||
  setweight(to_tsvector('english', author), 'B')) STORED;
CREATE INDEX books_search ON books USING gin (search);

SELECT title, author, ts_rank(search, q) AS rank
FROM books, websearch_to_tsquery('english', 'kitchen') q
WHERE search @@ q
ORDER BY rank DESC;
Output
ALTER TABLE
CREATE INDEX
       title       |   author   |   rank
-------------------+------------+-----------
 The Quiet Kitchen | Sofia Ruiz | 0.6079271
(1 row)

Why this works

The generated column stays in sync automatically. Weights let titles beat authors. The GIN index finds matches without scanning. And queries just use the search column.

keyvalue
GENERATEDalways in sync
setweightA beats B
GINno scanning
Queriessimple

Summary

Store the tsvector in a generated column, index it with GIN, and search stays fast. Next, fuzzy search for typos.

Key takeaways
  • tsvector column
  • GIN
  • Weights
Next up: Fuzzy Search with pg_trgm — typos welcome