AI Hints
Home›Elasticsearch Tutorial›Multi Get and By Query
Elasticsearch · Lesson 20 of 120

Update and Delete by Query

Change many at once.

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

The warehouse says every Granite brand product is now out of stock. You don't know their IDs, and there could be many. Update by query changes every document that matches.

  • Every Granite product
  • Unknown IDs
  • Update by query

Mark a brand out of stock

The query matches the brand Granite. The script sets in stock to false. Then we search for Granite products, and show only their in stock field. Run it. Six products were updated, and every one now says in stock false.

Dev Tools Consoletext
POST products/_update_by_query?refresh=true&filter_path=updated
{
  "query": { "match": { "brand": "Granite" } },
  "script": { "source": "ctx._source.in_stock = false" }
}

GET products/_search?filter_path=hits.hits._source.in_stock
{ "query": { "match": { "brand": "Granite" } } }
Output
# POST products/_update_by_query 200 OK
{"updated": 6}

# GET products/_search 200 OK
{
  "hits": {
    "hits": [
      {"_source": {"in_stock": false}},
      {"_source": {"in_stock": false}},
      {"_source": {"in_stock": false}},
      {"_source": {"in_stock": false}},
      {"_source": {"in_stock": false}},
      {"_source": {"in_stock": false}}
    ]
  }
}
Also uses _load
products

Delete by query

Delete by query removes every match. Here, every product in the Climbing category. Run it. Six products were deleted.

Dev Tools Consoletext
POST products/_delete_by_query?filter_path=deleted
{
  "query": { "match": { "category": "Climbing" } }
}
Output
{"deleted": 6}
Also uses _load
products

Summary

Update by query and delete by query change or remove every document that matches a query. Use them carefully. Next, let's load the whole catalog.

Key takeaways
  • _update_by_query
  • _delete_by_query
  • Use with care
Next up: Practice: Load the Catalog — all 49 products