Skip to content

Instantly share code, notes, and snippets.

@mraaroncruz
Forked from scottlowe/tsearch_migration.sql
Last active August 29, 2015 14:06
Show Gist options
  • Select an option

  • Save mraaroncruz/e144f0a4c4229effded8 to your computer and use it in GitHub Desktop.

Select an option

Save mraaroncruz/e144f0a4c4229effded8 to your computer and use it in GitHub Desktop.
-- Add the new tsvector column
ALTER TABLE articles ADD COLUMN tsv tsvector;
-- Create a function that will generate a tsvector from text data found in both the
-- title and body columns, but give a higher relevancy rating 'A' to the title data
CREATE FUNCTION articles_generate_tsvector() RETURNS trigger AS $$
begin
new.tsv :=
setweight(to_tsvector('pg_catalog.english', coalesce(new.title,'')), 'A') ||
setweight(to_tsvector('pg_catalog.english', coalesce(new.body,'')), 'B');
return new;
end
$$ LANGUAGE plpgsql;
-- When articles row data is inserted or updated, execute the function
-- that generates the tsvector data for that row
CREATE TRIGGER tsvector_articles_upsert_trigger BEFORE INSERT OR UPDATE
ON articles
FOR EACH ROW EXECUTE PROCEDURE articles_generate_tsvector();
-- When the migration is run, create tsvector data for all the existing records
UPDATE articles SET tsv =
setweight(to_tsvector('pg_catalog.english', coalesce(title,'')), 'A') ||
setweight(to_tsvector('pg_catalog.english', coalesce(body,'')), 'B');
-- Create an index for the tsv column that is specialised for tsvector data
CREATE INDEX articles_tsv_idx ON articles USING gin(tsv);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment