Search code examples
postgresqlfull-text-search

PostgreSQL: to_tsquery starts with and ends with search


Recently, I implemented a PostgreSQL 11 full-text search on a huge table I have in a system to solve the problem of hitting LIKE queries in it. This table has over 200 million rows and querying using to_tsquery worked pretty well for the column of type tsvector.

Now I need to hit the following queries but reading the documentation I couldn't find how to do it (or it's there and I didn't understand because full-text search is something new to me yet)

  • Starts with
  • Ends with

How can I make the query below return true only if the query is "The cat" (starts with) and "the book" (ends with), if it's possible in full-text search.

select to_tsvector('The cat is on the book') @@ to_tsquery('Cat')

Solution

  • I implemented a PostgreSQL 11 full-text search on a huge table I have in a system to solve the problem of hitting LIKE queries in it.

    How did you do that? FTS doesn't apply for LIKE queries. It applies for FTS queries, such as @@.

    You can't directly look for strings starting and ending with certain words. You can use the index to filter on cat and book, then refilter those rows for ones having them in the right place.

    select * from whatever where tsv_col @@ to_tsquery('cat & book') and text_col LIKE 'The cat % the book';
    

    Unless you want to match something like 'The cathe book' then you would have to do something else, with two different LIKE.