UpdateByQuery script update - when does ES update document?

For an index with the following mapping:

{
  "item_code": {
    "type": "keyword",
    "index": true,
  },
  "prices": {
    "type": "nested",
    "dynamic": false,
    "properties": {
      "pricing_hash": {
        "type": "keyword",
        "index": true,
      },
      "price": {
        "type": "float",
        "index": true,
      },
      "best_item": {
        "type": "boolean",
        "index": true,
      }
    }
  }
}

Consider the following update query:

POST /items/_update_by_query
{
  "query": {
    "bool": {
      "filter": [
        {
          "term": {
            "item_code": "ABC123"
          }
        }
      ]
    }
  },
  "script": {
    "source": "
int i;
boolean found;
for (new_price in params.new_prices) {
    found = false;
    if (ctx._source.prices == null) {
        ctx._source.prices = [];
    }
    for (i=0; i<ctx._source.prices.length; i++) {
        if (ctx._source.prices[i].pricing_hash == new_price.pricing_hash) {
            new_price.best_item = ctx._source.prices[i].best_item;
            ctx._source.prices[i] = new_price;
            found = true;
            break;
        }
    }
    if (found == false) {
        ctx._source.prices.add(new_price);
    }
}
",
    "lang": "painless",
    "params": {
      "new_prices": [
        {
          "pricing_hash": "abc12345",
          "price": 1.99,
          "best_item": true
        },
        {
          "pricing_hash": "def12345",
          "price": 2.99,
          "best_item": true
        }
      ]
    }
  }
}

(script indented for clarity).

If I'm indexing multiple prices into the same nested field in the same document, would ES internally save the document once at the end? Or every time a new price is changed or appended?

1 Like

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.