Complete the code to select all rows where the text column matches the search query using full-text search.
SELECT * FROM articles WHERE to_tsvector('english', content) @@ [1];
The plainto_tsquery function converts plain text to a tsquery for matching. It is used here with the language specified to match the content.
Complete the code to create a full-text search index on the 'content' column of the 'articles' table.
CREATE INDEX idx_content_search ON articles USING gin([1]);The to_tsvector function converts the text column into a tsvector type, which is needed for creating a GIN index for full-text search.
Fix the error in the query to search for articles containing the phrase 'full text search'.
SELECT * FROM articles WHERE to_tsvector('english', content) @@ [1];
The to_tsquery function requires operators like & to combine words for phrase search. The correct syntax uses 'full & text & search' with language specified.
Fill both blanks to create a query that ranks articles by relevance to the search term 'database'.
SELECT title, ts_rank([1], [2]) AS rank FROM articles WHERE to_tsvector('english', content) @@ to_tsquery('english', 'database') ORDER BY rank DESC;
The ts_rank function takes a tsvector and a tsquery to calculate relevance. The tsvector is created from the content column, and the tsquery is the search term.
Fill all three blanks to create a materialized view that stores articles with their search vectors for faster full-text search.
CREATE MATERIALIZED VIEW article_search AS SELECT id, title, content, [1] AS document_vector, [2] AS query_vector FROM articles, to_tsquery('english', [3]) query WHERE to_tsvector('english', content) @@ query;
The materialized view stores the tsvector of content as document_vector. The query vector is created with to_tsquery using the search term 'database'. The search term is passed as a string to to_tsquery.