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

tsvector and tsquery

Words in, words out.

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

A tsvector is a sorted list of word roots, called lexemes, with their positions. A tsquery is a search made of those roots, joined with and, or, and not.

  • tsvector: the text
  • tsquery: the search
  • Roots, called lexemes

See the lexemes

To tsvector shows each root and where it appeared. Small words like the and it are gone. And websearch to tsquery accepts search box style input, with quotes and minus signs. Run it. The roots, and the parsed searches.

query.sqlsql
SELECT to_tsvector('english', 'The plot makes no sense, and it drags.');

SELECT websearch_to_tsquery('english', 'gripping story -slow');
SELECT websearch_to_tsquery('english', '"brilliant ending" or recipes');
Output
             to_tsvector
-------------------------------------
 'drag':8 'make':3 'plot':2 'sens':5
(1 row)

    websearch_to_tsquery
----------------------------
 'grip' & 'stori' & !'slow'
(1 row)

      websearch_to_tsquery
---------------------------------
 'brilliant' <-> 'end' | 'recip'
(1 row)

Query operators

Ampersand means and. A bar means or. An exclamation mark means not. And the follows operator, less than minus greater than, finds words next to each other, like a phrase.

OperatorMeans
a & bboth
a | beither
!anot
a <-> ba followed by b

Summary

Tsvectors hold word roots, and tsqueries combine them with and, or, not and phrases. Next, ranking results and highlighting matches.

Key takeaways
  • Lexemes
  • & | !
  • websearch_to_tsquery
Next up: Ranking and Headlines — best first, with snippets