Docs Home

Chewy

3 min read
Last updated on Jul 7, 2023

Here's how to get started with Bonsai Elasticsearch and Ruby on Rails using Chewy.

Add Chewy to the Gemfile

In order to use the Chewy gem, add the gem to the Gemfile like so:

gem 'chewy'

Then run bundle install to install it.

Write an Initializer

A Chewy initializer will need to be written so that the Rails app can connect to your Bonsai cluster.

You can include your Bonsai cluster URL (located in Credentials of Bonsai dashboard in the initializer, but hard-coding your credentials is not recommended. Instead, export them manually in the application environment to an environment variable called BONSAI_URL.

We recommend using something like dotenv for this, but you can also set it manually like so:

# Substitute with your own Bonsai cluster URL:
export BONSAI_URL="https://abcd123:efg456@my-cluster-123456.us-west-2.bonsaisearch.net:443"

Heroku users will not need to do so, as their Bonsai cluster URL will already be in a Config Var of the same name.

Create a file called config/initializers/chewy.rb. With the environment variable in place, save the initializer with the following:

Chewy.settings = { host: ENV['BONSAI_URL'] }

The official Chewy documentation has more details on ways to modify and refine Chewy's behavior.

Configure Your Models

Any Rails model that you will want to be searchable with Elasticsearch will need to be configured to do so by creating a Chewy index definition and adding model-observing code.

For example, here's how we created an index definition for our demo app in app/chewy/users_index.rb:


class UsersIndex < Chewy::Index
  define_type User
end

Then, the User model is written like so:


class User < ApplicationRecord
  update_index('users#user') { self }
end

You can read more about configuring how a model will be ingested by Elasticsearch in the official Chewy documentation.

Indexing Your Documents

The Chewy gem comes with some Rake tasks for getting your documents into the cluster. Once you have set up your models as desired, run the following in your application environment:

bundle exec rake chewy:deploy

That will push your data into Elasticsearch and synchronize the data.

Next Steps

Chewy is a mature ODM with plenty of great features. Toptal (the maintainers of Chewy) have some great documentation exploring some of what Chewy can do: Elasticsearch for Ruby on Rails: A Tutorial to the Chewy Gem.

Ready to take a closer look at Bonsai?

Find out if Bonsai is a good fit for you in just 15 minutes.

Schedule a consultation
Calming Bonsai waves