{"_id":"5a8fae0468264c001f20cc3a","category":{"_id":"5a8fae0268264c001f20cc02","version":"5a8fae0268264c001f20cc00","project":"5633ebff7e9e880d00af1a53","__v":0,"sync":{"url":"","isSync":false},"reference":false,"createdAt":"2015-12-23T20:06:16.013Z","from_sync":false,"order":3,"slug":"quickstart-guides-1","title":"Quickstart Guides"},"project":"5633ebff7e9e880d00af1a53","user":"5633ec9b35355017003ca3f2","parentDoc":null,"version":{"_id":"5a8fae0268264c001f20cc00","project":"5633ebff7e9e880d00af1a53","__v":2,"createdAt":"2018-02-23T06:00:34.961Z","releaseDate":"2018-02-23T06:00:34.961Z","categories":["5a8fae0268264c001f20cc01","5a8fae0268264c001f20cc02","5a8fae0368264c001f20cc03","5a8fae0368264c001f20cc04","5a8fae0368264c001f20cc05","5a8fae0368264c001f20cc06","5a8fae0368264c001f20cc07","5a8fae0368264c001f20cc08","5a8fae0368264c001f20cc09","5abaa7eb72d6dc0028a07bf3"],"is_deprecated":false,"is_hidden":false,"is_beta":false,"is_stable":true,"codename":"","version_clean":"2.0.0","version":"2.0"},"__v":0,"updates":["5755e824eb85290e0069ac3f","584721274a6a0a25006ea529"],"next":{"pages":[],"description":""},"createdAt":"2015-12-23T19:23:16.460Z","link_external":false,"link_url":"","githubsync":"","sync_unique":"","hidden":false,"api":{"results":{"codes":[]},"settings":"","auth":"required","params":[],"url":""},"isReference":false,"order":3,"body":"Getting started with Ruby on Rails and Bonsai Elasticsearch is fast and easy. [Sign up](https://app.bonsai.io/signup) and create your first cluster to get started.\n\nThe following guide is for a simple integration. We will go through what gems to use, how to set up your client and your app, and how to index data. Finally, we'll walk through a basic way to set up a search page and display results. \n[block:callout]\n{\n  \"type\": \"warning\",\n  \"title\": \"Note\",\n  \"body\": \"These instructions are for users who want to use the official Elasticsearch Rails client. If you're using something like [SearchKick](https://github.com/ankane/searchkick), refer to the SearchKick documentation.\"\n}\n[/block]\n\n[block:api-header]\n{\n  \"title\": \"Set up the Elasticsearch client\"\n}\n[/block]\n## Add your cluster URL to your environment\n\nWe recommend adding your Bonsai Elasticsearch cluster URL to your environment (.env files) as a variable so you don't introduce security concerns by hard-coding it into your app. Add your cluster url to your `.env` file:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"BONSAI_URL=https://user:password:::at:::example-acme-development.us-east.bonsaisearch.net\",\n      \"language\": \"text\",\n      \"name\": \".env\"\n    }\n  ]\n}\n[/block]\nNext, add the `bonsai-elasticsearch-rails` gem to your Gemfile:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"gem 'bonsai-elasticsearch-rails'\",\n      \"language\": \"ruby\",\n      \"name\": \"Gemfile\"\n    }\n  ]\n}\n[/block]\nRun `bundle install`\n[block:callout]\n{\n  \"type\": \"warning\",\n  \"title\": \"Protip\",\n  \"body\": \"The `bonsai-elasticsearch-rails` gem is a wrapper to include and and initialize the `elasticsearch-rails` and `elasticsearch-model` gems in your app. You can always use those gems directly:\\n\\n```\\ngem 'elasticsearch-model'\\ngem 'elasticsearch-rails'\\n```\\n\\nand initialize a client:\\n\\n```\\n    Elasticsearch::Model.client = Elasticsearch::Client.new url: ENV['BONSAI_URL']\\n```\\n\\nApps should use the `bonsai-elasticsearch-rails` gem OR the model and rails gem plus an initializer, **but not both**. Setting up both will cause bugs later on.\"\n}\n[/block]\n\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Prepare models and rake tasks\"\n}\n[/block]\n## Prepare Rails Models\n\nPrepare your models to be indexed and searched by your cluster by including `Elasticsearch::Model`:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"class User < ActiveRecord::Base\\n  include Elasticsearch::Model\\n  include Elasticsearch::Model::Callbacks\\n\\n  ...\\n\\nend\",\n      \"language\": \"ruby\"\n    }\n  ]\n}\n[/block]\nDo this for any model you want to be searchable. Recall that Elasticsearch::Model is available to your app because the gem `bonsai-elasticsearch-rails` installs `elasticsearch-model` for you. See the full project for documentation here:\n\n - [https://github.com/elastic/elasticsearch-rails/tree/master/elasticsearch-model](https://github.com/elastic/elasticsearch-rails/tree/master/elasticsearch-model)\n\n## Explicitly limit what you index\n\nWe advise that you explicitly state what fields for your models you want to send to Elasticsearch. For example:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"class User < ApplicationRecord\\n  include Elasticsearch::Model\\n  include Elasticsearch::Model::Callbacks\\n  \\n  # only send to Elasticsearch what we care about searching and running stats on\\n  def as_indexed_json(*_)\\n    as_json(\\n      only: [:name, :email]\\n    )\\n  end\\nend\",\n      \"language\": \"ruby\",\n      \"name\": \"user.rb\"\n    }\n  ]\n}\n[/block]\n## Create a rake task\n\nDefine a rake task to import your models. Create a file  `lib/tasks/elasticsearch.rake`:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"require 'elasticsearch/rails/tasks/import'\",\n      \"language\": \"ruby\",\n      \"name\": \"elasticsearch.rake\"\n    }\n  ]\n}\n[/block]\nThis will let you index searchable records via rake tasks.\n[block:callout]\n{\n  \"type\": \"info\",\n  \"title\": \"Protip\",\n  \"body\": \"The `elasticsearch-rails gem` will create a new index for every searchable model.\"\n}\n[/block]\n\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Index data\"\n}\n[/block]\nBonsai does not support \"lazy\" index creation. In other words, **you will need to explicitly create your index before you can put documents there.** There are a few ways to do this. The best way is to use the rake task you (should have) set up in the last step. The first time you index your content, you'll want to set the `FORCE` parameter.\n\n## Run the rake task to import your data\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"rake environment elasticsearch:import:all FORCE=Y\",\n      \"language\": \"curl\"\n    }\n  ]\n}\n[/block]\nThe `FORCE` parameter will explicitly delete and recreate indices, so you probably don't want to use it frequently. Subsequent indexing tasks can drop this parameter.\n\nIf rake tasks aren't possible for some reason, you could also create your indices with with `curl`. So if you have a User model, then you could use the following command to create the index:\n\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"curl -XPUT http://username:password@redwood-12345.us-east-1.bonsai.io/users\",\n      \"language\": \"curl\",\n      \"name\": \"bash\"\n    }\n  ]\n}\n[/block]\nYou would need to repeat this for every model you plan to index.\n\n## Quick import commands\n\n- To import the records from a specific model, run:\n   `rake environment elasticsearch:import:model CLASS='User'`\n\n- To limit the scope of the records imported, run:\n   `rake environment elasticsearch:import:model CLASS='User' SCOPE='active'`\n\n- Force rebuilding the index (delete and create):\n   `rake environment elasticsearch:import:model CLASS='Article' FORCE=Y\n\n- Customize the batch size:\n   `rake environment elasticsearch:import:model CLASS='Article' BATCH=100`\n\n- Set target index name:\n   `rake environment elasticsearch:import:model CLASS='Article' INDEX='articles-new'`\n\n## Further reading\n\n**Elasticsearch Rails gem:**\n\n* [README](https://github.com/elasticsearch/elasticsearch-rails)\n* [Documentation](http://www.rubydoc.info/gems/elasticsearch-rails)\n\n\n**Elasticsearch-model gem:**\n\n* [Elasticsearch-model README](https://github.com/elasticsearch/elasticsearch-rails/tree/master/elasticsearch-model)\n* [Elasticsearch-model Documentation](http://www.rubydoc.info/gems/elasticsearch-model/)\n[block:api-header]\n{\n  \"title\": \"Search and Display Results\"\n}\n[/block]","excerpt":"How to integrate a Rails application with Elasticsearch.","slug":"ruby-on-rails","type":"basic","title":"Ruby on Rails"}

Ruby on Rails

How to integrate a Rails application with Elasticsearch.

Getting started with Ruby on Rails and Bonsai Elasticsearch is fast and easy. [Sign up](https://app.bonsai.io/signup) and create your first cluster to get started. The following guide is for a simple integration. We will go through what gems to use, how to set up your client and your app, and how to index data. Finally, we'll walk through a basic way to set up a search page and display results. [block:callout] { "type": "warning", "title": "Note", "body": "These instructions are for users who want to use the official Elasticsearch Rails client. If you're using something like [SearchKick](https://github.com/ankane/searchkick), refer to the SearchKick documentation." } [/block] [block:api-header] { "title": "Set up the Elasticsearch client" } [/block] ## Add your cluster URL to your environment We recommend adding your Bonsai Elasticsearch cluster URL to your environment (.env files) as a variable so you don't introduce security concerns by hard-coding it into your app. Add your cluster url to your `.env` file: [block:code] { "codes": [ { "code": "BONSAI_URL=https://user:password@example-acme-development.us-east.bonsaisearch.net", "language": "text", "name": ".env" } ] } [/block] Next, add the `bonsai-elasticsearch-rails` gem to your Gemfile: [block:code] { "codes": [ { "code": "gem 'bonsai-elasticsearch-rails'", "language": "ruby", "name": "Gemfile" } ] } [/block] Run `bundle install` [block:callout] { "type": "warning", "title": "Protip", "body": "The `bonsai-elasticsearch-rails` gem is a wrapper to include and and initialize the `elasticsearch-rails` and `elasticsearch-model` gems in your app. You can always use those gems directly:\n\n```\ngem 'elasticsearch-model'\ngem 'elasticsearch-rails'\n```\n\nand initialize a client:\n\n```\n Elasticsearch::Model.client = Elasticsearch::Client.new url: ENV['BONSAI_URL']\n```\n\nApps should use the `bonsai-elasticsearch-rails` gem OR the model and rails gem plus an initializer, **but not both**. Setting up both will cause bugs later on." } [/block] [block:api-header] { "type": "basic", "title": "Prepare models and rake tasks" } [/block] ## Prepare Rails Models Prepare your models to be indexed and searched by your cluster by including `Elasticsearch::Model`: [block:code] { "codes": [ { "code": "class User < ActiveRecord::Base\n include Elasticsearch::Model\n include Elasticsearch::Model::Callbacks\n\n ...\n\nend", "language": "ruby" } ] } [/block] Do this for any model you want to be searchable. Recall that Elasticsearch::Model is available to your app because the gem `bonsai-elasticsearch-rails` installs `elasticsearch-model` for you. See the full project for documentation here: - [https://github.com/elastic/elasticsearch-rails/tree/master/elasticsearch-model](https://github.com/elastic/elasticsearch-rails/tree/master/elasticsearch-model) ## Explicitly limit what you index We advise that you explicitly state what fields for your models you want to send to Elasticsearch. For example: [block:code] { "codes": [ { "code": "class User < ApplicationRecord\n include Elasticsearch::Model\n include Elasticsearch::Model::Callbacks\n \n # only send to Elasticsearch what we care about searching and running stats on\n def as_indexed_json(*_)\n as_json(\n only: [:name, :email]\n )\n end\nend", "language": "ruby", "name": "user.rb" } ] } [/block] ## Create a rake task Define a rake task to import your models. Create a file `lib/tasks/elasticsearch.rake`: [block:code] { "codes": [ { "code": "require 'elasticsearch/rails/tasks/import'", "language": "ruby", "name": "elasticsearch.rake" } ] } [/block] This will let you index searchable records via rake tasks. [block:callout] { "type": "info", "title": "Protip", "body": "The `elasticsearch-rails gem` will create a new index for every searchable model." } [/block] [block:api-header] { "type": "basic", "title": "Index data" } [/block] Bonsai does not support "lazy" index creation. In other words, **you will need to explicitly create your index before you can put documents there.** There are a few ways to do this. The best way is to use the rake task you (should have) set up in the last step. The first time you index your content, you'll want to set the `FORCE` parameter. ## Run the rake task to import your data [block:code] { "codes": [ { "code": "rake environment elasticsearch:import:all FORCE=Y", "language": "curl" } ] } [/block] The `FORCE` parameter will explicitly delete and recreate indices, so you probably don't want to use it frequently. Subsequent indexing tasks can drop this parameter. If rake tasks aren't possible for some reason, you could also create your indices with with `curl`. So if you have a User model, then you could use the following command to create the index: [block:code] { "codes": [ { "code": "curl -XPUT http://username:password@redwood-12345.us-east-1.bonsai.io/users", "language": "curl", "name": "bash" } ] } [/block] You would need to repeat this for every model you plan to index. ## Quick import commands - To import the records from a specific model, run: `rake environment elasticsearch:import:model CLASS='User'` - To limit the scope of the records imported, run: `rake environment elasticsearch:import:model CLASS='User' SCOPE='active'` - Force rebuilding the index (delete and create): `rake environment elasticsearch:import:model CLASS='Article' FORCE=Y - Customize the batch size: `rake environment elasticsearch:import:model CLASS='Article' BATCH=100` - Set target index name: `rake environment elasticsearch:import:model CLASS='Article' INDEX='articles-new'` ## Further reading **Elasticsearch Rails gem:** * [README](https://github.com/elasticsearch/elasticsearch-rails) * [Documentation](http://www.rubydoc.info/gems/elasticsearch-rails) **Elasticsearch-model gem:** * [Elasticsearch-model README](https://github.com/elasticsearch/elasticsearch-rails/tree/master/elasticsearch-model) * [Elasticsearch-model Documentation](http://www.rubydoc.info/gems/elasticsearch-model/) [block:api-header] { "title": "Search and Display Results" } [/block]