What is ts_rank in SQL?

0145

ts_rank is a function in PostgreSQL used to calculate the relevance or ranking of a tsvector against a tsquery in full-text search. It provides a score that indicates how well the text matches the search query, allowing you to sort results based on their relevance.

Syntax

ts_rank(tsvector, tsquery [, normalization])
  • tsvector: The text search vector you want to evaluate.
  • tsquery: The text search query you are matching against.
  • normalization (optional): A numeric value that adjusts the ranking score.

Example

Here’s an example of how to use ts_rank in a query:

SELECT title, content, ts_rank(search_vector, to_tsquery('english', 'search')) AS rank
FROM articles
WHERE search_vector @@ to_tsquery('english', 'search')
ORDER BY rank DESC;

In this example:

  • The query retrieves articles where the search_vector matches the term 'search'.
  • It calculates the rank of each article based on how well it matches the query.
  • The results are ordered by rank in descending order, showing the most relevant articles first.

0 Comments

no data
Be the first to share your comment!