Skip to content

Latest commit

 

History

History
60 lines (51 loc) · 1.4 KB

File metadata and controls

60 lines (51 loc) · 1.4 KB
endpoint update_by_query
lang php
es_version 9.3
client elasticsearch/elasticsearch==9.3.0

Elasticsearch 9.3 update_by_query endpoint (PHP example)

Use $client->updateByQuery() to update all documents matching a query using a script.

$response = $client->updateByQuery([
    'index' => 'products',
    'body'  => [
        'query' => [
            'term' => ['category' => 'electronics'],
        ],
        'script' => [
            'source' => 'ctx._source.price *= params.discount',
            'params' => ['discount' => 0.9],
        ],
    ],
]);
echo "Updated {$response['updated']} documents\n";

Handling conflicts

By default, version conflicts abort the operation. Set conflicts to proceed to skip conflicting documents and continue:

$response = $client->updateByQuery([
    'index'     => 'products',
    'conflicts' => 'proceed',
    'body'      => [
        'query'  => ['term' => ['in_stock' => true]],
        'script' => ['source' => 'ctx._source.in_stock = false'],
    ],
]);

Limiting scope

Use max_docs to cap the number of updates, and scroll_size to control batch size:

$response = $client->updateByQuery([
    'index'       => 'products',
    'max_docs'    => 500,
    'scroll_size' => 100,
    'body'        => [
        'query'  => ['match_all' => new \stdClass()],
        'script' => ['source' => 'ctx._source.rating += 0.1'],
    ],
]);