Add full text search support using TSV indexes
This commit is contained in:
33
example/db/migrate/20190405042247_add_search_column.rb
Normal file
33
example/db/migrate/20190405042247_add_search_column.rb
Normal 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
|
@ -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
|
||||
|
||||
|
Reference in New Issue
Block a user