Full text search in rails with pg_search

Setting up a search in you rails application is really easy. We’ll try to make one of our models searchable and we skip advanced functionality such as ignoring accents or taking mistypes into an account.

We will make use of an excellent pg_search gem so firstly, we have to add it to our Gemfile.

gem 'pg_search'

For this example we want to make a model searchable by one of its attributes. For that we will include PgSearch module and define a searching scope.

class Group < ActiveRecord::Base
  include PgSearch
  pg_search_scope :search_name, :against => [:name]
end

Last thing is to query the model inside the controller by calling the model’s scope with the query string.

class GroupsController < ApplicationController
  def search
    @groups = Group.search_name(params[:query])
  end
end

And that’s it. As you could see, introducing a simple search functionality in rails is simple, but there is much more in pg_search gem and postgresql itself and I recommend readme.md as a starting point.

With this gem and postgresql, you can search against multiple columns, query the application against different models with multisearch or even make use of advanced postgresql extensions such as fuzzy string matching, trigram search or ignoring accents.

It is an amazing tool which is straightforward to setup and use. So simple, much recommended!


Would you like to get the most interesting content about programming every Monday?
Sign up to Programming Digest and stay up to date!