How to Update a Document in Elasticsearch with NodeJS

Introduction

If you’re interacting with Elasticsearch through a NodeJS application, you’ll probably need to update a document at some point. It’s one of the most common tasks in database management– a user may update their address or credit card information, or the price of a product may need to be changed. Regardless of the situation, it’s important to know how to handle this task correctly. In this tutorial, we’ll explain how to update a document in Elasticsearch with NodeJS. If you’d prefer to skip the explanations and dive into the sample code, feel free to jump ahead to Just the Code.

Note: The exact code you’ll use to interact with 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 update a document in 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 before beginning this tutorial, you can review the application file we’re using, 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: ["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 update function on the elasticsearch client

Now that we’ve successfully pinged Elasticsearch, let’s try performing a simple update on a document. In your real-life applications, your updates may end up being more 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 perform an update. Let’s say we wanted to update the price of the “Multi-Grain Cereal” from 4.99 to 5.99. 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: ["localhost:9200"]
});

/* Update a Document */
client.update({
    index: "store",
    type: "products",
    id: "1",
    body: {
        // put the partial document under the `doc` key
        doc: {
            price: 5.99
        }
    }
})
.then(
    function(resp) {
        console.log("Successful update! The response was: ", resp);
    },
    function(err) {
        console.trace(err.message);
    }
);

In our example, we provide the update function with certain parameters: index: 'store', type: 'products', and then a description of the update we want inside the body parameter. Since our example is fairly simple, it doesn’t illustrate the full set of parameters available for the update function. For more information on these parameters, consult Elasticsearch’s documentation.

The update function that we’re using on the client has the definition shown below: `js client.update([params, [callback]]) `

Note You’ll notice that the function definition contains a callback parameter; however, we’ll be using promises instead in our example because they tend to be more readable. The API supports the use of promises as long as you do not provide a callback parameter.

It’s time to try out this code and see if it works. We added a bit of functionality to our code which executes when the promise is returned. The .then() functionality defines what to execute when the function update is successful and when it returns an error. You can see that we’ve added a console.log("Successful update! The response was: ", resp); to indicate success. Let’s run our code and look at the output:

$ node index.js
Successful update! The response was: { _index: 'store',
_type: 'products',
_id: '1',
_version: 4,
result: 'updated',
_shards: { total: 2, successful: 1, failed: 0 },
_seq_no: 5,
_primary_term: 2 }

Although we can see that we’ve received a success message, you may still want to confirm your update in Elasticsearch. The following code allows you to search for “Multi-Grain Cereal” and print the results to the console to verify that the price was changed. You can run this code as a separate NodeJS application or within the .then() part of your main application file:

/* Query Documents and Print to Console */
client.search({
    index: "store",
    type: "products",
    body: {
        query: {
            match_phrase: {
                name: "Multi-Grain Cereal"
            }
        }
    }
})
.then(
    function(resp) {
        console.log("Successful query! Here is the response:", resp.hits.hits);
    },
    function(err) {
        console.trace(err.message);
    }
);

The following output shows the response: `js _shards: { total: 0, successful: 0, failed: 0 } } Successful query! Here is the response: [ { _index: ‘store’, _type: ‘products’, _id: ‘1’, _score: 2.1470046, _source: { id: ‘1’, name: ‘Multi-Grain Cereal’, price: 5.99, quantity: 4, department: [Array] } } ] `

This proves without a doubt that our document was successfully updated.

Conclusion

Updating a document changes your data permanently, so it’s important to understand how to execute the operation correctly. In this tutorial, we explained how to update a document from a NodeJS application. With the step-by-step instructions in this guide, you’ll be ready to handle any update operations needed in your application. For information on all the various parameters available in the API, see Elasticsearch’s documentation.

Just the Code

If you’re already familiar with the concepts explained in this tutorial, here’s all the code you’ll need to update a document in Elasticsearch with NodeJS.

var elasticsearch = require("elasticsearch");

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

/* Update a Document */
client.update({
    index: "store",
    type: "products",
    id: "1",
    body: {
        // put the partial document under the `doc` key
        doc: {
            price: 5.99
        }
    }
})
.then(
    function(resp) {
        console.log("Successful update! The response was: ", resp);
    },
    function(err) {
        console.trace(err.message);
    }
);
/* Query Documents and Print to Console */
client.search({
    index: "store",
    type: "products",
    body: {
        query: {
            match_phrase: {
                name: "Multi-Grain Cereal"
            }
        }
    }
})
.then(
    function(resp) {
        console.log("Successful query! Here is the response:", resp.hits.hits);
    },
    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.