0

If I make the following query in postgres, is it calculating the ts_rank twice or just once? If it is calculating it twice, is it possible to make it calculate it only once?

SELECT id, name, "createdAt", price, ts_rank(document, to_tsquery(:query)) AS rank
FROM search_index
WHERE document @@ to_tsquery(:query)
ORDER BY ts_rank(document, to_tsquery(:query)) DESC;
1
  • Depends on whether the function is marked as immutable, stable, or volatile, and what the predicted cost is. Commented Aug 15, 2021 at 3:20

1 Answer 1

1

In this case, it should be calculated only once time. Postgres detects equal expressions. Generally, if you afraid about this, then you can calculate expression in subquery.

Some like:

SELECT c1, c1 FROM (SELECT exp AS c1) s;

The function to_tsquery() is very expensive without fulltext index. if you have fulltext index, and if there are only one hundreds selected records, then overhead of ts_rank should not be significant.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the additional info, I have set up a fulltext index using CREATE INDEX idx_fts_search ON search_index USING gin(document);.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.