How to Use Elasticsearch with NodeJS

Have a Database Problem? Speak with an Expert for Free
Get Started >>

Introduction

Elasticsearch is very compatible with popular applications that run on the backend. NodeJS for example, is one such application that when combined with Elasticsearch, you’re likely to expand your productivity. Because NodeJS is fast, your efficiency increases when you use Elasticsearch with it to run Javascript on the server-side and then let it run your backend. Speed and accurate search results are the co-benefits of the NodeJS and Elasticsearch. They work seamlessly together and enhance each other. So, if used as a main database, Elasticsearch delivers what you need; and if solely used as a search engine, you’ll still receive fast retrieval and responsiveness. This step-by-step tutorial shows you how use Elasticsearch with NodeJS in the simplest way so you can reap the full benefits of both applications.

Note that since system frameworks vary, the example code may require a slight modification to work with your particular platform. However, these basic guidelines of how to use NodeJS with Elasticsearch give you a workable solution in a tested code format.

If you’re already familiar with how NodeJS and Elasticsearch work together and would rather skip to the code, click here to go to Just the Code.

Prerequisites

  • Node.js Application – Install the NodeJS application. It’s available for Linux, macOS, and Windows platforms.

  • Elasticsearch – Download the latest version, then launch it after installation. It must be running as you follow the steps in this tutorial. (Note that NodeJS ran on a localhost:9200 for a recent demo.)

Make a test folder for the NodeJS application

Create a folder and name it nodejs-elasticsearch-demo. Next, right-click the folder and select “Open Terminal.” Run the npm init command. Hit “Enter.” This action will accept the default settings.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
$ npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install < pkg >` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (nodejs-elasticsearch-demo)
version: (1.0.0)
description:
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to /Users/alexthompson/Documents/500Rockets/OR01 - Object Rocket/_Elasticsearch-Markdown-GD/nodejs-elasticsearch-demo/package.json:

{
"name": "nodejs-elasticsearch-demo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo "Error: no test specified" && exit 1"
},
"author": "",
"license": "ISC"
}


Is this OK? (yes)
$

The new folder package.json you just created is located beneath the folder where the settings for dependenies are located in your system.

In NodeJS, install the Elasticsearch module

From the NodeJS package manager command line client (npm), install the Elasticsearch module. Go to application folder and in the terminal, run this command:

1
$ npm install elasticsearch

Wait while the npm module loads. The progress bars continually show the status of the installation. When finished, a confirmation message that looks somethng like this will appear.

1
2
added 12 packages from 6 contributors and audited 13 packages in 2.773s
found 0 vulnerabilities

You’re ready to make your primary script for Node.js applications

Create your Node.js primary script, and then join it to Elasticsearch via the client library. Here’s how to acomplish that.

To begin, make a file and call it anything you like, but it should be something simple and easy to remember. Name it index.js for this example.

Open the code editor program you’re used to and like the most. Type the following code at the top of the index.js file. (Note that this is done through the npm module elasticsearch you just downloaded.) :

1
var elasticsearch = require('elasticsearch');

Great! The library is imported. Elasticsearch and Node.js are connected. But there’s one more step to make the process complete. You need to configure Elasticsearch by creating a client so that gives you the ability to use the functions for effortless interaction.

Here’s what you do:

1
2
3
4
5
var elasticsearch = require('elasticsearch');

var client = new elasticsearch.Client({
hosts: [ 'http://localhost:9200']
});

Type in the code below to test the connection. You want to see the following message prompt: Connected to Elasticsearch was successful! You might see something other than a “successful” message, such as Cannot connect to Elasticsearch. though.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var elasticsearch = require('elasticsearch');

var client = new elasticsearch.Client({
hosts: [ 'http://localhost:9200']
});

client.ping({
requestTimeout: 30000,
}, function(error) {
if (error) {
console.error('Cannot connect to Elasticsearch.');
} else {
console.log('Connected to Elasticsearch was successful!');
}
});

Use the command below to test run your application:

1
2
$ node index.js
Connected to Elasticsearch was successful!

Look for the successful message prompt. If you receive a failed message, check the error code or troubleshooting tips in the console, if available. Use this pinging code to get started:

1
2
3
4
5
6
7
8
9
10
11
client.ping({
requestTimeout: 30000,
}, function(error) {
if (error) {
console.error('Cannot connect to Elasticsearch.');
console.error(error);

} else {
console.log('Connected to Elasticsearch was successful!');
}
});

Conclusion

From this tutorial, you learned how to use Elasticsearch with NodeJS. The scalable network applications are endless with this fearless combination, so get started today. Feel free to reach out to us to find out more.

Just the Code

Here’s the example code to connect Node.js to Elasticsearch. Please be sure to have both Node.js and Elasticsearch applications installed and running prior to testing.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var elasticsearch = require('elasticsearch');

var client = new elasticsearch.Client({
hosts: [ 'http://localhost:9200']
});

client.ping({
requestTimeout: 30000,
}, function(error) {
if (error) {
console.error('Cannot connect to Elasticsearch.');
console.error(error);

} else {
console.log('Connected to Elasticsearch was successful!');
}
});

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.