AI Hints
Home›Elasticsearch Tutorial›Create, Update, Delete
Elasticsearch · Lesson 14 of 120

Updating Documents

Change one field.

⏱ 2 min read▶ Video at 12:37🎓 Free
Watch this lesson in the Elasticsearch courseWatch on YouTube ↗Full Elasticsearch course

The price of the Basecamp tent just dropped. You don't want to send the whole product again. The update API changes only the fields you name.

  • Price dropped
  • Don't resend it all
  • Update one field

A partial update

POST to_update, and the ID. Inside doc, put only the fields to change. Then we fetch the document. Run it. The price changed, and every other field is still there.

Dev Tools Consoletext
POST products/_update/1?filter_path=result
{
  "doc": { "price": 199.99 }
}

GET products/_source/1
Output
# POST products/_update/1 200 OK
{"result": "updated"}

# GET products/_source/1 200 OK
{
  "name": "Basecamp 2-Person Tent",
  "brand": "TrailCo",
  "price": 199.99,
  "in_stock": true,
  "tags": ["camping"]
}
Also uses _setup.http
PUT products
{ "settings": { "number_of_replicas": 0 } }

PUT products/_doc/1?refresh=true
{ "name": "Basecamp 2-Person Tent", "brand": "TrailCo", "price": 237.99, "in_stock": true, "tags": ["camping"] }

Update with a script

A script can change a field based on its current value. Here we take ten percent off the price, and add a new tag to the tags list. Run it. The price is now two hundred and fourteen, and the tags list has sale.

Dev Tools Consoletext
POST products/_update/1?filter_path=result
{
  "script": {
    "source": "ctx._source.price *= 0.9; ctx._source.tags.add('sale')"
  }
}

GET products/_source/1
Output
# POST products/_update/1 200 OK
{"result": "updated"}

# GET products/_source/1 200 OK
{
  "name": "Basecamp 2-Person Tent",
  "brand": "TrailCo",
  "price": 214.191,
  "in_stock": true,
  "tags": ["camping", "sale"]
}
Also uses _setup.http
PUT products
{ "settings": { "number_of_replicas": 0 } }

PUT products/_doc/1?refresh=true
{ "name": "Basecamp 2-Person Tent", "brand": "TrailCo", "price": 237.99, "in_stock": true, "tags": ["camping"] }

Summary

Underscore update with doc changes only the fields you send. A script can change values based on what's there. Next, deleting.

Key takeaways
  • _update
  • doc: {...}
  • script
Next up: Deleting Documents — and whole indexes