Skip to content

Instantly share code, notes, and snippets.

@kascote
Last active February 16, 2016 22:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kascote/bd8706ef41e1d06a650f to your computer and use it in GitHub Desktop.
Save kascote/bd8706ef41e1d06a650f to your computer and use it in GitHub Desktop.
Postgres Full Text Search
CREATE TABLE messages (
title text,
body text,
tsv tsvector
);
CREATE TRIGGER tsvectorupdate BEFORE INSERT OR UPDATE
ON messages FOR EACH ROW EXECUTE PROCEDURE
tsvector_update_trigger(tsv, 'english', title, body);
INSERT INTO messages VALUES('title here', 'the body text is here');
--- using a custom trigger and set weight on columns
CREATE FUNCTION messages_search_trigger() RETURNS trigger AS $$
begin
new.searchable_column :=
setweight(to_tsvector('english', coalesce(new.title,'')), 'A') ||
setweight(to_tsvector('english', coalesce(new.body,'')), 'D');
return new;
end
$$ LANGUAGE plpgsql;
CREATE TRIGGER search_update_on_messages BEFORE INSERT OR UPDATE
ON messages FOR EACH ROW EXECUTE PROCEDURE messages_search_trigger();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment