Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save thomasgallagher/2c983844ea7f61b7d899775901bf016e to your computer and use it in GitHub Desktop.
Save thomasgallagher/2c983844ea7f61b7d899775901bf016e to your computer and use it in GitHub Desktop.
pg_search partial weighted matching over first_name, last_name, location on User
class AddTsvectorToUsers < ActiveRecord::Migration
def up
add_column :users, :tsv, :tsvector
add_index :users, :tsv, using: 'gin'
execute <<-SQL
CREATE TRIGGER tsvectorupdate BEFORE INSERT OR UPDATE
ON users FOR EACH ROW EXECUTE PROCEDURE
tsvector_update_trigger(
tsv, 'pg_catalog.simple', first_name, last_name, location
);
SQL
now = Time.current.to_s(:db)
update "UPDATE users SET updated_at = '#{now}'"
end
def down
execute <<-SQL
DROP TRIGGER tsvectorupdate
ON users
SQL
remove_index :users, :tsv
remove_column :users, :tsv
end
end
class SearchesController < ApplicationController
def new
@query = params[:query]
@users = User.search_by_name_and_location(@query).limit(5)
end
end
class User < ActiveRecord::Base
include PgSearch
pg_search_scope :search_by_name_and_location, against: { first_name: 'A', last_name: 'B', location: 'C' }, using: { tsearch: { tsvector_column: 'tsv', prefix: true } }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment