AI Hints
Home›PostgreSQL Tutorial›Full-Text Search
PostgreSQL · Lesson 58 of 120

Full-Text Search

Search words, not text.

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

Each book has a short blurb. A shopper searches for stories about a detective in a village. Like would need that exact text. Full text search understands words, so it matches detectives and villages too.

  • 'detective village'
  • LIKE fails
  • Match words

To tsvector turns each blurb into searchable words. To tsquery turns the search into words to find, here detective and village. The at at operator checks for a match. Run it. Two mysteries, though neither blurb has that exact text.

query.sqlsql
SELECT title
FROM books
WHERE to_tsvector('english', blurb) @@ to_tsquery('english', 'detectives & villages');
Output
        title
---------------------
 The Silent Orchard
 Murder at Mill Lane
(2 rows)

LIKE vs full-text

Like matches exact characters, with no idea of words. Full text search splits text into words, removes small words like the, and reduces words to their root, so detectives matches detective.

LIKE

  • Exact textNo word formsNo ranking

Full-text

  • Words and rootsIgnores 'the', 'a'Can rank results

Summary

Full text search matches words and their forms, using tsvector, tsquery and at at. Next, a closer look at those two types.

Key takeaways
  • to_tsvector
  • to_tsquery
  • @@
Next up: tsvector and tsquery — words in, words out