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

Practice: Book Search

Words and typos.

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

Let's build Riverside's search box. First, try full text search. If it finds nothing, fall back to fuzzy matching. So kitchen and kitchn both work.

  • Full-text first
  • Fuzzy fallback
  • Both work

A search function

The function tries full text search first. If that returns nothing, it returns fuzzy matches instead. Then we call it with a correct word, and a typo. Run it. Both searches find The Quiet Kitchen.

query.sqlsql
CREATE EXTENSION pg_trgm;
CREATE FUNCTION find_books(q text) RETURNS SETOF text LANGUAGE plpgsql AS $$
BEGIN
  RETURN QUERY SELECT title FROM books
    WHERE to_tsvector('english', title) @@ websearch_to_tsquery('english', q);
  IF NOT FOUND THEN
    RETURN QUERY SELECT title FROM books WHERE q <% title
      ORDER BY word_similarity(q, title) DESC LIMIT 3;
  END IF;
END $$;

SELECT find_books('kitchen') AS exact;
SELECT find_books('kitchn')  AS fuzzy;
Output
CREATE EXTENSION
CREATE FUNCTION
       exact
-------------------
 The Quiet Kitchen
(1 row)

       fuzzy
-------------------
 The Quiet Kitchen
(1 row)

What we used

Full text search for real words. Trigrams for typos. A small PL pg SQL function to choose between them. Functions come up properly in a later lesson.

keyvalue
Full-textreal words
pg_trgmtypos
plpgsqlthe glue
Laterfunctions in depth

Summary

Full text first, then fuzzy, makes a friendly search box. Next, transactions.

Key takeaways
  • Full-text
  • Fuzzy
  • Fallback
Next up: Transactions — all or nothing