From 0d1062d9952590b2d5a48a3aee17d95de4aac10c Mon Sep 17 00:00:00 2001 From: Maxime Delporte Date: Thu, 13 Nov 2025 18:52:59 +0100 Subject: [PATCH] Adding full-text search. --- .idea/dictionaries/project.xml | 2 ++ internal/data/movies.go | 7 ++++++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/.idea/dictionaries/project.xml b/.idea/dictionaries/project.xml index 10e27c6..a7ca38b 100644 --- a/.idea/dictionaries/project.xml +++ b/.idea/dictionaries/project.xml @@ -2,7 +2,9 @@ httprouter + plainto servemux + tsvector \ No newline at end of file diff --git a/internal/data/movies.go b/internal/data/movies.go index 79011e0..cb91693 100644 --- a/internal/data/movies.go +++ b/internal/data/movies.go @@ -195,9 +195,14 @@ func (m MovieModel) Delete(id int64) error { // GetAll : Returns a slice of movies. Although we're not using them right now, we've set this up to accept the various filter parameters as arguments func (m MovieModel) GetAll(title string, genres []string, filters Filters) ([]*Movie, error) { // Construct the SQL query to retrieve all movie records. + // to_tsvector('simple', title) transforms 'The Breakfast Club' into 'breakfast' 'club' 'the'. The 'simple' parameter's value is the configuration. + // plainto_tsquery('simple', $1) takes a search value and turns it into a formatted query term that PostgreSQL full-text search can understand. As an example : "The Club" would result in the query term 'the' & 'club' + // The @@ operator is the matches operator. To continue the example, the query term 'the' & 'club' will match rows which contain both lexemes 'the' and 'club'. query := ` SELECT id, created_at, title, year, runtime, genres, version FROM movies + WHERE (to_tsvector('simple', title) @@ plainto_tsquery('simple', $1) OR $1 = '') + AND (genres @> $2 OR $2 = '{}') ORDER BY id` // Create a context with a 3-second timeout @@ -205,7 +210,7 @@ func (m MovieModel) GetAll(title string, genres []string, filters Filters) ([]*M defer cancel() // Use QueryContext() to execute the query. This returns a sql.Rows resultset containing the result - rows, err := m.DB.QueryContext(ctx, query) + rows, err := m.DB.QueryContext(ctx, query, title, pq.Array(genres)) if err != nil { return nil, err }