Bonsai Elasticsearch integrates with your node.js app quickly and easily, whether you’re running on Heroku or self hosting.
First, make sure to add the Elasticsearch.js client to your dependencies list:
package.json:
"dependencies": { "elasticsearch": "10.1.2" ....
You’ll also want to make sure the client is installed locally for testing purposes:
$ npm install --save elasticsearch $ npm install
Self-hosted users: when you sign up with Bonsai and create a cluster, it will be provisioned with a custom URL that looks like https://user:pass@my-awesome-cluster.us-east-1.bonsai.io. Make note of this URL because it will be needed momentarily.
Heroku users: you’ll want to make sure that you’ve added Bonsai Elasticsearch to your app. Visit our addons page to see available plans. You can add Bonsai to your app through the dashboard, or by running:
$ heroku addons:create bonsai: -a
Update your index.js file with the following:
index.js:
var bonsai_url = process.env.BONSAI_URL; var elasticsearch = require('elasticsearch'); var client = new elasticsearch.Client({ host: bonsai_url, log: 'trace' }); // Test the connection: // Send a HEAD request to "/" and allow // up to 30 seconds for it to complete. client.ping({ requestTimeout: 30000, }, function (error) { if (error) { console.error('elasticsearch cluster is down!'); } else { console.log('All is well'); } });
The code above does several things:
- Pulls your Bonsai URL from the environment (you never want to hard-code this value – it’s a bad practice)
- Adds the Elasticsearch.js library
- Instantiates the client using your private Bonsai URL
- Pings the cluster to test the connection
Self-hosted users: You will need to take an additional step and add your Bonsai URL to your server/dev environment. Something like this should work:
$ export BONSAI_URL="https://username:password@my-awesome-cluster-123.us-east-1.bonsai.io"
Heroku users: You don’t need to worry about this step. The environment variable is automatically populated for you when you add Bonsai Elasticsearch to your app. You can verify that it exists by running:
$ heroku config:get BONSAI_URL
Go ahead and spin up your node app with npm start
. Heroku users can also push the changes to Heroku, and monitor the logs with heroku logs --tail
. Either way, you should see something like this:
Elasticsearch INFO: 2016-02-03T23:44:41Z Adding connection to https://nodejs-test-012345.us-east-1.bonsai.io/ Elasticsearch DEBUG: 2016-02-03T23:44:41Z Request complete Elasticsearch TRACE: 2016-02-03T23:44:41Z -> HEAD https://nodejs-test-012345.us-east-1.bonsai.io:443/?hello=elasticsearch <- 200
The above output indicates that the client was successfully initiated and was able to contact the cluster.
Questions? Problems? Feel free to ping our support if something isn’t working right and we’ll do what we can to help out.