Simplified polymorphic full text + similarity search based on postgres
MIT License
Simplified polymorphic full text + similarity search based on postgres.
NOTE: This project is narrower in scope and more opinionated than pg_search.
Add the gem to your project
bundle add polysearch
Run the generator
bundle exec rails g polysearch:migration
You can also specify a datatype that your app uses for primary keys (default is bigint
).
For example, if your application uses uuid
primary keys, you install the migration like this.
bundle exec rails g polysearch:migration uuid
Migrate the database
bundle exec rails db:migrate
Update the model(s) you'd like to search
class User < ApplicationRecord
include Polysearch::Searchable
after_save_commit :update_polysearch
def to_tsvectors
[
make_tsvector(first_name, weight: "A"),
make_tsvector(last_name, weight: "A"),
make_tsvector(nickname, weight: "B")
]
end
end
If you have existing records that need to create/update a polysearch record, you can save them like this.
User.find_each(&:update_polysearch)
Start searching
User.create first_name: "Shawn", last_name: "Spencer", nickname: "Maverick"
# find natural language matches (faster)
User.full_text_search("shawn")
# find similarity matches, best for misspelled search terms (slower)
User.similarity_search("shwn")
# perform both a full text search and similarity search
User.combined_search("shwn")
# perform a full text search and fall back to similarity search (faster than combined_search)
User.polysearch("shwn")
# calculate counts (explicitly pass :id to omit search rankings)
User.full_text_search("shawn").count(:id)
User.similarity_search("shwn").count(:id)
User.combined_search("shwn").count(:id)
User.polysearch("shwn").count(:id)
The gem is available as open source under the terms of the MIT License.