public static function updateAllCounters($counters, $condition = [])
{
$primaryKeys = static::primaryKeysByCondition($condition);
if (empty($primaryKeys) || empty($counters)) {
return 0;
}
$bulkCommand = static::getDb()->createBulkCommand(["index" => static::index(), "type" => static::type()]);
foreach ($primaryKeys as $pk) {
$script = '';
foreach ($counters as $counter => $value) {
$script .= "ctx._source.{$counter} += {$counter};\n";
}
$bulkCommand->addAction(["update" => ["_id" => $pk]], ["script" => $script, "params" => $counters, "lang" => "groovy"]);
}
$response = $bulkCommand->execute();
$n = 0;
$errors = [];
foreach ($response['items'] as $item) {
if (isset($item['update']['status']) && $item['update']['status'] == 200) {
$n++;
} else {
$errors[] = $item['update'];
}
}
if (!empty($errors) || isset($response['errors']) && $response['errors']) {
throw new Exception(__METHOD__ . ' failed updating records counters.', $errors);
}
return $n;
}