Full Text Search With Sunspot and Mongoid in Ruby on Rails
First of all, we must add necessary gems to gemfile
1 2 3 4 5 6
sunspot_solr gem is added to development group because it will run only in development environment.
Now, we can run bundle command:
We can use the generator of the sunpot gem for creating configuration file.
Then we can run Solr server:
After these steps, our project now ready for implementation of searching functionality
In the model of our project we will implement necessary steps for searching.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
We have fields like
:title, :address, :description and one more searchable attribute as
:category_name. We boosted
:title field because we want to find more related searches in this field. And we searched our model with it’s association’s attribute. We created a method called
category_name and we added it to searchable block.
After initial implementation in the model layer, we have not indexes for doing searches properly. So we need to index all of our records according to searchable attributes. For doing this you can run rails console and index all records.
*There are another solutions for indexing the data but this one was enough for me.
We implemented our model and now we can search through them.
1 2 3 4 5 6 7
In this search method, we called a
solr_search method on
Place model and passed
params[:q] to with fulltext method. Notice that we used
solr_search method instead of
search, because mongoid has also a method named
search and they are conflicting in the Mongoid case.
We implemented a basic full text search functionality. Sunspot gem has advance configurations for more complicated situations and needs. If you find this useful, share it for other people.