How to Query Elasticsearch using NodeJS

Introduction

If you’re running a NodeJS application with Elasticsearch, you’re getting the best of both words: the efficiency of NodeJS and the powerful search functionality of Elasticsearch. To make the most of this search functionality, it’s important to know how to query Elasticsearch. In this tutorial, we’ll provide step-by-step instructions that show how to query Elasticsearch using NodeJS. If you’re already familiar with the basics of Elasticsearch and NodeJS, feel free to skip ahead to Just the Code

Note: The exact code you’ll use to query Elasticsearch will vary depending on your specific system parameters; however, the sample code used in this tutorial will provide the basic understanding you need.

Prerequisites

Before we can attempt to query Elasticsearch with NodeJS, it’s important to confirm that a few prerequisites are in place. The following system requirements are necessary to complete the task: NodeJS and npm need to be installed A NodeJS application must be set up * Elasticsearch needs to be installed and running

Note: In our example, Elasticsearch is running locally on the default port; therefore, you’ll see us communicate with Elasticsearch at "localhost:9200". If your installation of Elasticsearch is running on a different server, your calls to it will take a slightly different format: "YOURDOMAIN.com:9200".

Getting up to Speed

Although we’re assuming that you already have a NodeJS application set up as one of the prerequisites for this tutorial, you can review our main application file index.js in order to get a clear idea of what we’re starting with:

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!");
}
}
);

You can run this application using a command like:

$ node index.js

In response, you’ll see a console message indicating whether your application is connected to Elasticsearch or not. If you don’t happen to have an application created already, this sample code can get you off to a good start.

Let’s take a minute to look at what’s going on in this code. First, we import the "elasticsearch" module. This provides all the functions we’ll need to interact with Elasticsearch. Then, we created a client that connects to the port where Elasticsearch is running. Once we have that connection to Elasticsearch set up, we’ll be doing all of our interactions with Elasticsearch through client. Finally, we simply ping Elasticsearch to confirm that we have a connection.

Use the search function on the elasticsearch client

Now that we’ve successfully pinged Elasticsearch, let’s try running a simple query. In your real-life applications, your queries may end up being quite complex, but for our example, we’ll start with something simple.

For our example, we’ll use a sample index called store, which represents a small grocery store. Our store index contains a type called products which lists all of the store’s products. We’ll keep our dataset simple by including just a handful of products with a small number of fields: id, price, quantity, and department. The JSON shown below can be used to create our dataset:

idnamepricequantitydepartment
1Multi-Grain Cereal4.994Packaged Foods
21lb Ground Beef3.9929Meat and Seafood
3Dozen Apples2.4912Produce
4Chocolate Bar1.292Packaged Foods, Checkout
51 Gallon Milk3.2916Dairy
60.5lb Jumbo Shrimp5.2912Meat and Seafood
7Wheat Bread1.295Bakery
8Pepperoni Pizza2.995Frozen
912 Pack Cola5.296Packaged Foods
10Lime Juice0.9920Produce
1112 Pack Cherry Cola5.595Packaged Foods
121 Gallon Soy Milk3.3910Dairy
131 Gallon Vanilla Soy Milk3.499Dairy
141 Gallon Orange Juice3.294Juice

The following code shows the mapping:

{
"mappings": {
"products": {
"properties" : {
"name": { "type": "text"},
"price": { "type": "double"},
"quantity": { "type": "integer"},
"department": { "type": "keyword"}
}
}
}
}
'

Now that we’ve created our dataset, we can issue a query. Let’s say we wanted to query Elasticsearch for products that have the word “Cola” in their name. The following code shows how this would be done. It may look a bit complex, but the explanations that follow will clarify what’s going on:

var elasticsearch = require("elasticsearch");

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

client
.search({
index: "store",
type: "products",
body: {
query: {
match: {
name: "Cola"
}
}
}
})
.then(
function(resp) {
console.log("Successful query! Here is the response:", resp);
},
function(err) {
console.trace(err.message);
}
);

Let’s take a closer look at what’s going on in this code. We used the search function on the client and gave it the appropriate parameters needed to do a query. In this case, we supplied the parameters index: 'store', type: 'products', and then a description of our query in the body parameter. Inside the body, we used the match query type parameter and specified that we want to find any products with the term “Cola” in the "name" field.

The function definition for search is shown below:

client.search([params, [callback]]);

Now that we’ve reviewed our code, let’s see if it works. For testing purposes, we added some logging code that will execute after the query. The .then() functionality defines what will happen whether the function search is successful or returns an error. In our example, we’ve added a console.log("Successful query! Here is the response:", resp); to indicate success. Let’s run the code and see what output we get:

$ node index.js
Successful query! Here is the response: { took: 1,
timed_out: false,
_shards: { total: 5, successful: 5, skipped: 0, failed: 0 },
hits:
{ total: 2, max_score: 1.3469357, hits: [ [Object], [Object] ] } }

As you can see, the query returned total: 2 documents. This proves that our query worked successfully, because our dataset does indeed have two products with the term “Cola”:

9 | 12 Pack Cola | 5.29 | 6 | Packaged Foods 11| 12 Pack Cherry Cola | 5.59 | 5 | Packaged Foods

Conclusion

If you’re interacting with Elasticsearch in a NodeJS application, you’ll probably need to run a query at some point. Fortunately, it’s easy to add a query to your code using the Elasticsearch client module from npm. Although the query shown in our example was a simple one, the same step-by-step instructions can be used for even the most complex queries. With the explanations provided in this tutorial, you’ll be able to query Elasticsearch with NodeJS and take your applications to the next level.

Just the Code

If you’re already familiar with the concepts explained in this tutorial, here’s all the code you’ll need to query Elasticsearch with NodeJS:

var elasticsearch = require("elasticsearch");

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

client
.search({
index: "store",
type: "products",
body: {
query: {
match: {
name: "Cola"
}
}
}
})
.then(
function(resp) {
console.log("Successful query! Here is the response:", resp);
},
function(err) {
console.trace(err.message);
}
);

Pilot the ObjectRocket platform free for 30 Days

It's easy to get started. Imagine the time you'll save by not worrying about database management. Let's do this!

PILOT FREE FOR 30 DAYS

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.