SQL

Implement Full-Text Search with Ranking in PostgreSQL

Harness PostgreSQL's powerful full-text search capabilities using `tsvector` and `tsquery` to perform efficient and ranked keyword searches on text fields.

SELECT
    id,
    title,
    description,
    ts_rank(to_tsvector('english', title || ' ' || description), websearch_to_tsquery('english', 'search terms')) AS rank
FROM
    articles
WHERE
    to_tsvector('english', title || ' ' || description) @@ websearch_to_tsquery('english', 'search terms')
ORDER BY
    rank DESC
LIMIT 10;
How it works: This snippet shows how to perform a full-text search in PostgreSQL, a crucial feature for any application with search functionality. It converts the `title` and `description` fields into a `tsvector` (a special data type for full-text search) and then uses the `websearch_to_tsquery` function to create a query from user input like 'search terms'. The `@@` operator checks for a match, and `ts_rank` calculates a relevance score, allowing results to be ordered by how closely they match the search terms.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs