Add full text search support using TSV indexes

This commit is contained in:
Vikram Rangnekar
2019-04-05 01:44:30 -04:00
parent 907ada9263
commit d1bf87e19c
8 changed files with 134 additions and 8 deletions

View File

@ -0,0 +1,33 @@
class AddSearchColumn < ActiveRecord::Migration[5.1]
def self.up
add_column :products, :tsv, :tsvector
add_index :products, :tsv, using: "gin"
say_with_time("Adding trigger to update the ts_vector column") do
execute <<-SQL
CREATE FUNCTION products_tsv_trigger() RETURNS trigger AS $$
begin
new.tsv :=
setweight(to_tsvector('pg_catalog.english', coalesce(new.name,'')), 'A') ||
setweight(to_tsvector('pg_catalog.english', coalesce(new.description,'')), 'B');
return new;
end
$$ LANGUAGE plpgsql;
CREATE TRIGGER tsvectorupdate BEFORE INSERT OR UPDATE ON products FOR EACH ROW EXECUTE PROCEDURE products_tsv_trigger();
SQL
end
end
def self.down
say_with_time("Removing trigger to update the tsv column") do
execute <<-SQL
DROP TRIGGER tsvectorupdate
ON products
SQL
end
remove_index :products, :tsv
remove_column :products, :tsv
end
end

View File

@ -10,7 +10,7 @@
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 2019_03_22_200743) do
ActiveRecord::Schema.define(version: 2019_04_05_042247) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
@ -36,6 +36,8 @@ ActiveRecord::Schema.define(version: 2019_03_22_200743) do
t.bigint "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.tsvector "tsv"
t.index ["tsv"], name: "index_products_on_tsv", using: :gin
t.index ["user_id"], name: "index_products_on_user_id"
end