DEV Community

PostgreSQL Full Text Search Rank by Position

The author describes optimizing full-text search in PostgreSQL for blog post titles. Initially, `to_tsvector` was used dynamically, causing slowdowns. To improve performance, a `search_vector` column storing pre-processed tsvectors was added and indexed using GIN. This significantly sped up searches using `to_tsquery`. PostgreSQL's `ts_rank` function provides result ranking, but lacks position-based ranking. The `POSITION` function was used to determine the search term's position within the title. A custom ranking was created combining `ts_rank` and the inverse of the position for better relevance scoring. A minor adjustment avoids division by zero. The final query orders results by this combined ranking. The solution works well for single-term searches. However, searching multiple terms requires careful consideration due to the limitations of `POSITION` compared to the flexibility of `to_tsquery`. The author provides links to relevant PostgreSQL documentation.
favicon
dev.to
dev.to