Sub topic 1
Why LIKE is not enough for text search
Prerequisites
This chapter assumes you can run SELECT, WHERE, and ORDER BY queries, create a table, and run queries in psql or another SQL client. You should also know how to create an index.
Why LIKE is not enough
LIKE and ILIKE match literal characters. A pattern such as '%run%' finds running, but it misses runs and ran. It also matches words inside other words, so '%cat%' finds category. Searching long text this way also scans every row, and a leading wildcard prevents a normal B-tree index from helping.
PostgreSQL full-text search solves this by converting text into normalized word forms, called lexemes, before it compares them.
Text search configurations and the language setting
A text search configuration is a set of rules for one language. It decides how text is split into words, which common words (stop words) are dropped, and how words are reduced to a base form. The 'english' configuration drops words such as the and reduces foxes to fox. Always pass the same configuration to both the document and the query, or the lexemes will not match.
Documents as tsvector: lexemes and positions
A tsvector is the processed form of a document. Each lexeme is stored with the position where it appeared.
SELECT to_tsvector('english', 'The quick brown foxes jumped over the lazy dogs');The output lists lexemes such as 'fox':4. The word the is gone because it is a stop word. The number after the colon is the word's position in the text.
Queries as tsquery: &, |, ! and <->
A tsquery is a search expression built from lexemes and operators:
&means AND.|means OR.!means NOT.<->means the words must be next to each other, in order.
Use to_tsquery when you write the operators yourself:
SELECT to_tsquery('english', 'fox & jump');Matching documents with @@
The @@ operator returns true when a tsvector satisfies a tsquery.
SELECT to_tsvector('english', 'The quick brown foxes jumped over the lazy dogs')
@@ to_tsquery('english', 'fox & jump') AS matches;This returns true, even though the query word jump does not appear in the text. The text has jumped, which both sides reduce to the lexeme jump.
Exercise
Will to_tsvector('english', 'Runners ran home') @@ to_tsquery('english', 'run & home') return true? Explain why, using the word forms involved.
Show answer
Yes. The stemmer reduces Runners and ran to lexemes that match run, and home matches directly. The @@ operator therefore returns true. A LIKE '%run%' search would miss ran, which shows the difference from LIKE.