Sub topic 3
Documents as `tsvector`: Lexemes and Positions
This chapter assumes basic SQL, PostgreSQL tables and indexes, and experience running queries in psql or another SQL client. You will learn how PostgreSQL represents searchable text internally.
From text to lexemes
A tsvector is PostgreSQL's searchable representation of a document. It contains normalized words called lexemes. A lexeme is not always the original word. PostgreSQL can lowercase words, remove stop words, and reduce related words to a common stem.
Use to_tsvector to convert text:
SELECT to_tsvector(
'english',
'The quick brown foxes jumped over the lazy dogs'
) AS document;The result is similar to this:
'brown':3 'dog':9 'fox':4 'jump':5 'lazi':8 'quick':2The exact display can vary with the PostgreSQL configuration. foxes becomes fox, jumped becomes jump, and common words such as the and over are removed. These transformations make searches for related word forms match the same document.
| Input word | Possible English lexeme | Reason |
|---|---|---|
| `foxes` | `fox` | Stemming reduces a plural form |
| `jumped` | `jump` | Stemming reduces a past-tense form |
| `the` | omitted | It is a stop word |
A tsvector stores each distinct lexeme once. Its optional positions record where that lexeme appeared in the original token sequence. Positions start at one and include tokens that were later removed as stop words. PostgreSQL uses positions for phrase matching and some ranking calculations.
Inspecting positions
You can assign a tsvector value explicitly, but most applications create one from text:
SELECT
to_tsvector('english', 'PostgreSQL makes searching searchable') AS document,
strip(to_tsvector('english', 'PostgreSQL makes searching searchable'))
AS without_positions;strip removes position and weight information while keeping the lexemes. This can reduce storage, but it also removes information needed by features such as phrase searches and position-aware ranking.
A tsvector is not a copy of the source text. It does not preserve capitalization, punctuation, or the original spelling. Keep the original text column for display, and use the tsvector for matching and ranking.
Checking the result
When a search does not behave as expected, first inspect the generated vector. Compare it with the query's lexemes rather than comparing the original strings character by character.
Exercise
Why might a search for jump match a document containing jumped when both use the english configuration?
Show answer
The English configuration stems both words to the lexeme jump, so the document and query can match.