Postgresql – PG fulltext search: Boost factor for word in the title

full-text-searchpostgresql

I use PostgreSQL full text search and it works fine.

The database schema is simple. A page has a title and a content.

Up to now I just index the string which I get by joining title+content.

In the future I would like to adapt the ranking. If a search term is in the title
of a document, then I would like to rank this page higher.

How can I influence the search ranking in PostgreSQL?

Best Answer

Yes, you can do that using ts_rank:

You can use setweight to give different parts of the text search vector different weight:

SELECT * from atable
WHERE (to_tsvector('english', title) ||
       to_tsvector('english', content)
      ) @@ to_tsquery('english', 'happy <-> home')
ORDER BY ts_rank(setweight(to_tsvector('english', title), 'A') ||
                 setweight(to_tsvector('english', content), 'C'),
                 to_tsquery('english', 'happy <-> home'));

Then the title will be ranked higher (weight A) than the content (weight C).