Upserts

edit

Upserts are "Update or Insert" operations. This means an upsert will attempt to run your update script, but if the document does not exist (or the field you are trying to update doesn’t exist), default values will be inserted instead.

$params = [
    'index' => 'my_index',
    'type' => 'my_type',
    'id' => 'my_id',
    'body' => [
        'script' => 'ctx._source.counter += count',
        'params' => [
            'count' => 4
        ],
        'upsert' => [
            'counter' => 1
        ]
    ]
];

$response = $client->update($params);