Sub topic 3
Documents as tsvector: lexemes and positions
This chapter assumes you can run queries in psql, and that you have read the earlier chapters on why LIKE falls short and on text search configurations. It covers what a tsvector contains, how PostgreSQL builds one, and which details later affect matching and ranking.
What a tsvector is
A tsvector is a sorted list of distinct lexemes, each with an optional list of positions. A lexeme is a normalized word: lowercased, usually stemmed, and stripped of stop words. A position is the word's ordinal place in the original text, counting from 1.
SELECT to_tsvector('english', 'The quick brown foxes jumped over the lazy dogs');'brown':3 'dog':9 'fox':4 'jump':5 'lazi':8 'quick':2Four things in this output matter:
foxesbecamefox,jumpedbecamejump, andlazybecamelazi. The stemmer produces roots, not dictionary words, so a lexeme can look misspelled.theandoverare absent. They are stop words in theenglishconfiguration.- Positions keep the gaps.
quickis at 2 andbrownat 3, butfoxis at 4 andjumpat 5 because the original word order is preserved. Removed words still occupy a position. - Lexemes are sorted alphabetically, not in document order. A
tsvectoris a lookup structure, not a copy of the text.
How a tsvector is built
to_tsvector(config, text) runs a pipeline.
The diagram block follows in the required form.
The parser classifies each token as a word, number, email address, URL, hyphenated word, and so on. The configuration maps each token type to a chain of dictionaries. Each dictionary either returns lexemes, drops the token, or passes it to the next dictionary. A later chapter covers dictionaries in detail.
Repeated words and the configuration's effect
When a word appears several times, its lexeme lists every position.
SELECT to_tsvector('english', 'cat and hat and cat');'cat':1,5 'hat':3The configuration changes the result. The simple configuration lowercases but does not stem or remove stop words.
SELECT to_tsvector('simple', 'The foxes were running') AS simple_vec,
to_tsvector('english', 'The foxes were running') AS english_vec; simple_vec | english_vec
-----------------------------------------+------------------
'foxes':2 'running':4 'the':1 'were':3 | 'fox':2 'run':4The english vector keeps positions 2 and 4 for fox and run, so the gaps left by the and were remain.
Casting text to a tsvector
Casting with ::tsvector does not parse, stem, or remove anything. It only splits on whitespace, sorts, and removes duplicates.
SELECT 'The Fat Rats'::tsvector;
SELECT 'fat:2 cat:3 fat:7'::tsvector;
SELECT 'fat:2A cat:3B'::tsvector;'Fat' 'Rats' 'The'
'cat':3 'fat':2,7
'cat':3B 'fat':2AThe first result keeps its capital letters, so it will not match a stemmed query. Casting is useful for tests and for loading vectors that were built elsewhere. Production documents should go through to_tsvector. The third statement shows that a position can carry a weight label (A to D), which a later chapter covers.
Positions and phrase matching
Positions make phrase search possible. The <-> operator means "followed immediately by", and <N> means "exactly N positions later".
SELECT to_tsvector('english', 'quick the fox') @@ to_tsquery('english', 'quick <-> fox') AS adjacent,
to_tsvector('english', 'quick the fox') @@ to_tsquery('english', 'quick <2> fox') AS two_apart; adjacent | two_apart
----------+-----------
f | tThe stop word the is not stored, but it still uses position 2. The phrase quick the fox therefore matches quick <2> fox and not quick <-> fox. Keep this in mind when users type phrases that contain stop words. The query constructors in the next chapters handle it for you.
Inspecting and editing a tsvector
PostgreSQL ships functions for working with vectors directly.
| Function or operator | Purpose | Column | Column |
|---|---|---|---|
| `length(tsvector)` | Number of distinct lexemes | ||
| `strip(tsvector)` | Removes positions and weights, which shrinks the vector | ||
| `tsvector_to_array(tsvector)` | Returns the lexemes as a `text[]` | ||
| `setweight(tsvector, 'A')` | Labels every position with a weight | ||
| `tsvector \ | \ | tsvector` | Concatenates, shifting the right side's positions |
Concatenation adjusts positions so they continue after the left operand.
SELECT 'a:1 b:2'::tsvector || 'c:1 d:2 b:3'::tsvector;'a':1 'b':2,4 'c':3 'd':4The right operand's positions were shifted by 2, the largest position on the left. You will use || to combine a weighted title vector and a weighted body vector.
Limits and edge cases
- A position is capped at 16383. Words past that point in a very long document are all recorded at 16383, so phrase matching and ranking are unreliable for them.
- Each lexeme keeps at most 256 positions. Further occurrences are not recorded.
- A single lexeme must be shorter than 2 kB, and the whole tsvector must be smaller than 1 MB.
to_tsvectorraises an error when a document exceeds the size limit, so truncate or split very large documents before indexing them. - A
NULLinput gives aNULLvector, andNULL @@ queryis not true. Wrap nullable columns incoalesce(col, ''). - Numbers, email addresses, and URLs are tokens too. A URL can produce several lexemes at the same position, one for the whole URL and others for its parts. Use
ts_debugto see exactly what happened.
Two-argument to_tsvector(text) uses default_text_search_config. That function is not immutable, so it cannot be used in an index expression or a generated column. Always pass the configuration name explicitly.
What comes next
A tsvector describes a document. The next chapter covers the other half, the tsquery, and how the @@ operator compares the two.
Exercise
What does SELECT to_tsvector('english', 'Cats chase the cats') return, and why do the stop word the and the repeated word appear the way they do?
Show answer
It returns 'cat':1,4 'chase':2. Both Cats and cats are lowercased and stemmed to cat, so that lexeme lists positions 1 and 4. the is a stop word, so it is dropped, but it still occupies position 3, which is why cat is at 4 and not 3.
Exercise
A user searches for the phrase "quick fox" and your documents contain "quick the fox". With the english configuration, does the <-> operator match? Which operator would match, and what is the reason?
Show answer
<-> does not match. The stop word the is removed from the vector but still uses a position, so quick is at 1 and fox at 3. The operator <2> matches because it allows exactly two positions between the lexemes.