Created
May 7, 2016 07:53
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class SearchesController < ApplicationController | |
def new | |
@query = params[:query] | |
@users = User.search_by_name_and_location(@query).limit(5) | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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