Class yii\elasticsearch\ActiveRecord

Inheritanceyii\elasticsearch\ActiveRecord » yii\db\BaseActiveRecord
Available since extension's version2.0
Source Code https://github.com/yiisoft/yii2-elasticsearch/blob/master/ActiveRecord.php

ActiveRecord is the base class for classes representing relational data in terms of objects.

This class implements the ActiveRecord pattern for the fulltext search and data storage Elasticsearch.

For defining a record a subclass should at least implement the attributes() method to define attributes. IMPORTANT: The primary key (the _id attribute) MUST NOT be included in attributes().

The following is an example model called Customer:

class Customer extends \yii\elasticsearch\ActiveRecord
{
    public function attributes()
    {
        return ['name', 'address', 'registration_date'];
    }
}

You may override index() and type() to define the index and type this record represents. Types are being deprecated, and it is recommended to have a single type per index. For more information read about removal of mapping types. For Elasticsearch 7 and later (as configured in yii\elasticsearch\Connection, type() is ignored.

Public Properties

Hide inherited properties

Property Type Description Defined By
$_id mixed The primary key of the record. yii\elasticsearch\ActiveRecord
$explanation array|null An explanation for each hit on how its score was computed. yii\elasticsearch\ActiveRecord
$highlight array|null A list of arrays with highlighted excerpts indexed by field names. yii\elasticsearch\ActiveRecord
$score float Returns the score of this record when it was retrieved via a find() query. yii\elasticsearch\ActiveRecord

Public Methods

Hide inherited methods

Method Description Defined By
arrayAttributes() A list of attributes that should be treated as array valued when retrieved through yii\elasticsearch\ActiveQuery::fields(). yii\elasticsearch\ActiveRecord
attributes() Returns the list of all attribute names of the model. yii\elasticsearch\ActiveRecord
delete() yii\elasticsearch\ActiveRecord
deleteAll() Deletes rows in the table using the provided conditions. yii\elasticsearch\ActiveRecord
find() yii\elasticsearch\ActiveRecord
findAll() yii\elasticsearch\ActiveRecord
findOne() yii\elasticsearch\ActiveRecord
get() Gets a record by its primary key. yii\elasticsearch\ActiveRecord
getDb() Returns the database connection used by this AR class. yii\elasticsearch\ActiveRecord
getExplanation() yii\elasticsearch\ActiveRecord
getHighlight() yii\elasticsearch\ActiveRecord
getOldPrimaryKey() yii\elasticsearch\ActiveRecord
getPrimaryKey() Alias to get_id(). Returns the primary key value. yii\elasticsearch\ActiveRecord
getScore() yii\elasticsearch\ActiveRecord
get_id() Returns the _id attribute that holds the primary key (for compatibility with relations) yii\elasticsearch\ActiveRecord
index() yii\elasticsearch\ActiveRecord
insert() Inserts a document into the associated index using the attribute values of this record. yii\elasticsearch\ActiveRecord
instantiate() Creates an active record instance. yii\elasticsearch\ActiveRecord
link() yii\elasticsearch\ActiveRecord
mget() Gets a list of records by its primary keys. yii\elasticsearch\ActiveRecord
optimisticLock() This method has no effect in Elasticsearch ActiveRecord. yii\elasticsearch\ActiveRecord
populateRecord() yii\elasticsearch\ActiveRecord
primaryKey() This method defines the attribute that uniquely identifies a record. yii\elasticsearch\ActiveRecord
setPrimaryKey() Alias to set_id(). Sets the primary key value. yii\elasticsearch\ActiveRecord
set_id() Sets the _id attribute that holds the primary key (for compatibility with relations) yii\elasticsearch\ActiveRecord
type() Returns the name of the type of this record. yii\elasticsearch\ActiveRecord
unlinkAll() Destroys the relationship in current model. yii\elasticsearch\ActiveRecord
update() yii\elasticsearch\ActiveRecord
updateAll() Updates all records that match a certain condition. yii\elasticsearch\ActiveRecord
updateAllCounters() Updates all matching records using the provided counter changes and conditions. yii\elasticsearch\ActiveRecord

Protected Methods

Hide inherited methods

Method Description Defined By
primaryKeysByCondition() Performs a quick and highly efficient scroll/scan query to get the list of primary keys that satisfy the given condition. If condition is a list of primary keys (e.g.: ['_id' => ['1', '2', '3']]), the query is not performed for performance considerations. yii\elasticsearch\ActiveRecord
updateInternal() yii\elasticsearch\ActiveRecord
validateViaRelationLink() Validates model so that it does not contain array as its keys while linking. yii\elasticsearch\ActiveRecord

Property Details

Hide inherited properties

$_id public property

The primary key of the record. Can only be written to for new records, otherwise read-only.

public mixed $_id null
$explanation public property

An explanation for each hit on how its score was computed. This property is read-only.

public array|null $explanation null
$highlight public property

A list of arrays with highlighted excerpts indexed by field names. This property is read-only.

public array|null $highlight null
$score public property

Returns the score of this record when it was retrieved via a find() query. This property is read-only.

public float $score null

Method Details

Hide inherited methods

arrayAttributes() public method

A list of attributes that should be treated as array valued when retrieved through yii\elasticsearch\ActiveQuery::fields().

If not listed by this method, attributes retrieved through yii\elasticsearch\ActiveQuery::fields() will converted to a scalar value when the result array contains only one value.

public string[] arrayAttributes ( )
return string[]

List of attribute names. Must be a subset of attributes().

                public function arrayAttributes()
{
    return [];
}

            
attributes() public method

Returns the list of all attribute names of the model.

This method must be overridden by child classes to define available attributes. IMPORTANT: The primary key (the _id attribute) MUST NOT be included in attributes().

Attributes are names of fields of the corresponding Elasticsearch document.

public string[] attributes ( )
return string[]

List of attribute names.

throws \yii\base\InvalidConfigException

if not overridden in a child class.

                public function attributes()
{
    throw new InvalidConfigException('The attributes() method of Elasticsearch ActiveRecord has to be implemented by child classes.');
}

            
delete() public method

public integer|boolean delete ( $options = [] )
$options array

Options given in this parameter are passed to Elasticsearch as request URI parameters. These are among others:

  • routing define shard placement of this record.
  • parent by giving the primaryKey of another record this defines a parent-child relation
  • timeout timeout waiting for a shard to become available.
  • replication the replication type for the delete/index operation (sync or async).
  • consistency the write consistency of the index/delete operation.
  • refresh refresh the relevant primary and replica shards (not the whole index) immediately after the operation occurs, so that the updated document appears in search results immediately.

Please refer to the Elasticsearch documentation for more details on these options.

The following parameters are Yii specific:

  • optimistic_locking set this to true to enable optimistic locking, avoid updating when the record has changed since it has been loaded from the database. Yii will set the version parameter to the value stored in version. See the Elasticsearch documentation for details.

    Make sure the record has been fetched with a version before. This is only the case for records fetched via get() and mget() by default. For normal queries, the _version field has to be fetched explicitly.

return integer|boolean

The number of rows deleted, or false if the deletion is unsuccessful for some reason. Note that it is possible the number of rows deleted is 0, even though the deletion execution is successful.

throws \yii\db\StaleObjectException

if optimistic locking is enabled and the data being deleted is outdated.

throws yii\elasticsearch\Exception

in case delete failed.

                public function delete($options = [])
{
    if (!$this->beforeDelete()) {
        return false;
    }
    if (isset($options['optimistic_locking']) && $options['optimistic_locking']) {
        if ($this->_version === null) {
            throw new InvalidArgumentException('Unable to use optimistic locking on a record that has no version set. Refer to the docs of ActiveRecord::delete() for details.');
        }
        $options['version'] = $this->_version;
        unset($options['optimistic_locking']);
    }
    try {
        $result = static::getDb()->createCommand()->delete(
            static::index(),
            static::type(),
            $this->getOldPrimaryKey(false),
            $options
        );
    } catch (Exception $e) {
        // HTTP 409 is the response in case of failed optimistic locking
        // https://www.elastic.co/guide/en/elasticsearch/guide/current/optimistic-concurrency-control.html
        if (isset($e->errorInfo['responseCode']) && $e->errorInfo['responseCode'] == 409) {
            throw new StaleObjectException('The object being deleted is outdated.', $e->errorInfo, $e->getCode(), $e);
        }
        throw $e;
    }
    $this->setOldAttributes(null);
    $this->afterDelete();
    if ($result === false) {
        return 0;
    } else {
        return 1;
    }
}

            
deleteAll() public static method

Deletes rows in the table using the provided conditions.

WARNING: If you do not specify any condition, this method will delete ALL rows in the table.

For example, to delete all customers whose status is 3:

Customer::deleteAll(['status' => 3]);
public static integer deleteAll ( $condition = [] )
$condition array

The conditions that will be passed to the where() method when building the query. Please refer to ActiveQuery::where() on how to specify this parameter.

return integer

The number of rows deleted

throws yii\elasticsearch\Exception

on error.

                public static function deleteAll($condition = [])
{
    $primaryKeys = static::primaryKeysByCondition($condition);
    if (empty($primaryKeys)) {
        return 0;
    }
    $bulkCommand = static::getDb()->createBulkCommand([
        "index" => static::index(),
        "type" => static::type(),
    ]);
    foreach ($primaryKeys as $pk) {
        $bulkCommand->addDeleteAction($pk);
    }
    $response = $bulkCommand->execute();
    $n = 0;
    $errors = [];
    foreach ($response['items'] as $item) {
        if (isset($item['delete']['status']) && $item['delete']['status'] == 200) {
            if (isset($item['delete']['found']) && $item['delete']['found']) {
                # ES5 uses "found"
                $n++;
            } elseif (isset($item['delete']['result']) && $item['delete']['result'] == "deleted") {
                # ES6 uses "result"
                $n++;
            }
        } else {
            $errors[] = $item['delete'];
        }
    }
    if (!empty($errors) || isset($response['errors']) && $response['errors']) {
        throw new Exception(__METHOD__ . ' failed deleting records.', $errors);
    }
    return $n;
}

            
find() public static method

public static yii\elasticsearch\ActiveQuery find ( )
return yii\elasticsearch\ActiveQuery

The newly created yii\elasticsearch\ActiveQuery instance.

                public static function find()
{
    return Yii::createObject(ActiveQuery::className(), [get_called_class()]);
}

            
findAll() public static method

public static void findAll ( $condition )
$condition

                public static function findAll($condition)
{
    if (!ArrayHelper::isAssociative($condition)) {
        return static::mget(is_array($condition) ? array_values($condition) : [$condition]);
    }
    $condition = static::filterCondition($condition);
    return static::find()->andWhere($condition)->all();
}

            
findOne() public static method

public static void findOne ( $condition )
$condition

                public static function findOne($condition)
{
    if (!is_array($condition)) {
        return static::get($condition);
    }
    if (!ArrayHelper::isAssociative($condition)) {
        $records = static::mget(array_values($condition));
        return empty($records) ? null : reset($records);
    }
    $condition = static::filterCondition($condition);
    return static::find()->andWhere($condition)->one();
}

            
get() public static method

Gets a record by its primary key.

public static static|null get ( $primaryKey, $options = [] )
$primaryKey mixed

The primaryKey value

$options array

Options given in this parameter are passed to Elasticsearch as request URI parameters. Please refer to the Elasticsearch documentation for more details on these options.

return yii\elasticsearch\ActiveRecord|null

The record instance or null if it was not found.

                public static function get($primaryKey, $options = [])
{
    if ($primaryKey === null) {
        return null;
    }
    $command = static::getDb()->createCommand();
    $result = $command->get(static::index(), static::type(), $primaryKey, $options);
    if ($result && $result['found']) {
        $model = static::instantiate($result);
        static::populateRecord($model, $result);
        $model->afterFind();
        return $model;
    }
    return null;
}

            
getDb() public static method

Returns the database connection used by this AR class.

By default, the "elasticsearch" application component is used as the database connection. You may override this method if you want to use a different database connection.

public static yii\elasticsearch\Connection getDb ( )
return yii\elasticsearch\Connection

The database connection used by this AR class.

                public static function getDb()
{
    return \Yii::$app->get('elasticsearch');
}

            
getExplanation() public method (available since version 2.0.5)

public array|null getExplanation ( )
return array|null

An explanation for each hit on how its score was computed.

                public function getExplanation()
{
    return $this->_explanation;
}

            
getHighlight() public method

public array|null getHighlight ( )
return array|null

A list of arrays with highlighted excerpts indexed by field names.

                public function getHighlight()
{
    return $this->_highlight;
}

            
getOldPrimaryKey() public method

public void getOldPrimaryKey ( $asArray false )
$asArray

                public function getOldPrimaryKey($asArray = false)
{
    $pk = static::primaryKey()[0];
    if ($this->getIsNewRecord()) {
        $id = null;
    } else {
        $id = $this->_id;
    }
    if ($asArray) {
        return [$pk => $id];
    } else {
        return $id;
    }
}

            
getPrimaryKey() public method
Deprecated since 2.1.0

Alias to get_id(). Returns the primary key value.

public mixed getPrimaryKey ( $asArray false )
$asArray boolean

                public function getPrimaryKey($asArray = false)
{
    $pk = static::primaryKey()[0];
    if ($asArray) {
        return [$pk => $this->$pk];
    } else {
        return $this->$pk;
    }
}

            
getScore() public method

public float getScore ( )
return float

Returns the score of this record when it was retrieved via a find() query.

                public function getScore()
{
    return $this->_score;
}

            
get_id() public method

Returns the _id attribute that holds the primary key (for compatibility with relations)

public mixed get_id ( )

                public function get_id()
{
    $pk = static::primaryKey()[0];
    return $this->$pk;
}

            
index() public static method

public static string index ( )
return string

The name of the index this record is stored in.

                public static function index()
{
    return Inflector::pluralize(Inflector::camel2id(StringHelper::basename(get_called_class()), '-'));
}

            
insert() public method

Inserts a document into the associated index using the attribute values of this record.

This method performs the following steps in order:

  1. call beforeValidate() when $runValidation is true. If validation fails, it will skip the rest of the steps;
  2. call afterValidate() when $runValidation is true.
  3. call beforeSave(). If the method returns false, it will skip the rest of the steps;
  4. insert the record into database. If this fails, it will skip the rest of the steps;
  5. call afterSave();

In the above step 1, 2, 3 and 5, events EVENT_BEFORE_VALIDATE, EVENT_BEFORE_INSERT, EVENT_AFTER_INSERT and EVENT_AFTER_VALIDATE will be raised by the corresponding methods.

Only the dirtyAttributes will be inserted into database.

If the primary key is not set (null) during insertion, it will be populated with a randomly generated value after insertion.

For example, to insert a customer record:

$customer = new Customer;
$customer->name = $name;
$customer->email = $email;
$customer->insert();
public boolean insert ( $runValidation true, $attributes null, $options = [] )
$runValidation boolean

Whether to perform validation before saving the record. If the validation fails, the record will not be inserted into the database.

$attributes array

List of attributes that need to be saved. Defaults to null, meaning all attributes will be saved.

$options array

Options given in this parameter are passed to Elasticsearch as request URI parameters. These are among others:

  • routing define shard placement of this record.
  • parent by giving the primaryKey of another record this defines a parent-child relation

Please refer to the Elasticsearch documentation for more details on these options.

By default the op_type is set to create if model primary key is present.

return boolean

Whether the attributes are valid and the record is inserted successfully.

                public function insert($runValidation = true, $attributes = null, $options = [ ])
{
    if ($runValidation && !$this->validate($attributes)) {
        return false;
    }
    if (!$this->beforeSave(true)) {
        return false;
    }
    $values = $this->getDirtyAttributes($attributes);
    if ($this->getPrimaryKey() !== null) {
        $options['op_type'] = isset($options['op_type']) ? $options['op_type'] : 'create';
    }
    $response = static::getDb()->createCommand()->insert(
        static::index(),
        static::type(),
        $values,
        $this->getPrimaryKey(),
        $options
    );
    if ($response === false) {
        return false;
    }
    $pk = static::primaryKey()[0];
    $this->$pk = $response['_id'];
    if ($pk != '_id') {
        $values[$pk] = $response['_id'];
    }
    $this->_version = $response['_version'];
    $this->_score = null;
    $changedAttributes = array_fill_keys(array_keys($values), null);
    $this->setOldAttributes($values);
    $this->afterSave(true, $changedAttributes);
    return true;
}

            
instantiate() public static method

Creates an active record instance.

This method is called together with populateRecord() by yii\elasticsearch\ActiveQuery. It is not meant to be used for creating new records directly.

You may override this method if the instance being created depends on the row data to be populated into the record. For example, by creating a record based on the value of a column, you may implement the so-called single-table inheritance mapping.

public static static instantiate ( $row )
$row array

Row data to be populated into the record. This array consists of the following keys:

  • _source: refers to the attributes of the record.
  • _type: the type this record is stored in.
  • _index: the index this record is stored in.
return yii\elasticsearch\ActiveRecord

The newly created active record

                public static function instantiate($row)
{
    return new static;
}

            
link() public method

public void link ( $name, $model, $extraColumns = [] )
$name
$model
$extraColumns

mget() public static method

Gets a list of records by its primary keys.

public static array mget ( array $primaryKeys, $options = [] )
$primaryKeys array

An array of primaryKey values

$options array

Options given in this parameter are passed to Elasticsearch as request URI parameters.

Please refer to the Elasticsearch documentation for more details on these options.

return array

The record instances, or empty array if nothing was found

                public static function mget(array $primaryKeys, $options = [])
{
    if (empty($primaryKeys)) {
        return [];
    }
    if (count($primaryKeys) === 1) {
        $model = static::get(reset($primaryKeys));
        return $model === null ? [] : [$model];
    }
    $command = static::getDb()->createCommand();
    $result = $command->mget(static::index(), static::type(), $primaryKeys, $options);
    $models = [];
    foreach ($result['docs'] as $doc) {
        if ($doc['found']) {
            $model = static::instantiate($doc);
            static::populateRecord($model, $doc);
            $model->afterFind();
            $models[] = $model;
        }
    }
    return $models;
}

            
optimisticLock() public method

This method has no effect in Elasticsearch ActiveRecord.

Elasticsearch ActiveRecord uses native Optimistic locking. See update() for more details.

public void optimisticLock ( )

                public function optimisticLock()
{
    return null;
}

            
populateRecord() public static method

public static void populateRecord ( $record, $row )
$record yii\elasticsearch\ActiveRecord

The record to be populated. In most cases this will be an instance created by instantiate() beforehand.

$row array

Attribute values (name => value)

                public static function populateRecord($record, $row)
{
    $attributes = [];
    if (isset($row['_source'])) {
        $attributes = $row['_source'];
    }
    if (isset($row['fields'])) {
        // reset fields in case it is scalar value
        $arrayAttributes = $record->arrayAttributes();
        foreach ($row['fields'] as $key => $value) {
            if (!isset($arrayAttributes[$key]) && count($value) === 1) {
                $row['fields'][$key] = reset($value);
            }
        }
        $attributes = array_merge($attributes, $row['fields']);
    }
    parent::populateRecord($record, $attributes);
    $pk = static::primaryKey()[0];
    $record->_id = $row[$pk];
    $record->_highlight = isset($row['highlight']) ? $row['highlight'] : null;
    $record->_score = isset($row['_score']) ? $row['_score'] : null;
    $record->_version = isset($row['_version']) ? $row['_version'] : null; // TODO version should always be available...
    $record->_explanation = isset($row['_explanation']) ? $row['_explanation'] : null;
}

            
primaryKey() public static method

This method defines the attribute that uniquely identifies a record.

The name of the primary key attribute is _id, and can not be changed.

Elasticsearch does not support composite primary keys in the traditional sense. However to match the signature of the \yii\db\ActiveRecordInterface this methods returns an array instead of a single string.

public static string[] primaryKey ( )
return string[]

Array of primary key attributes. Only the first element of the array will be used.

                final public static function primaryKey()
{
    return ['_id'];
}

            
primaryKeysByCondition() protected static method (available since version 2.0.4)

Performs a quick and highly efficient scroll/scan query to get the list of primary keys that satisfy the given condition. If condition is a list of primary keys (e.g.: ['_id' => ['1', '2', '3']]), the query is not performed for performance considerations.

See also:

protected static array primaryKeysByCondition ( $condition )
$condition array

Please refer to ActiveQuery::where() on how to specify this parameter

return array

Primary keys that correspond to given conditions

                protected static function primaryKeysByCondition($condition)
{
    $pkName = static::primaryKey()[0];
    if (count($condition) == 1 && isset($condition[$pkName])) {
        $primaryKeys = (array)$condition[$pkName];
    } else {
        //fetch only document metadata (no fields), 1000 documents per shard
        $query = static::find()->where($condition)->asArray()->source(false)->limit(1000);
        $primaryKeys = [];
        foreach ($query->each('1m') as $document) {
            $primaryKeys[] = $document['_id'];
        }
    }
    return $primaryKeys;
}

            
setPrimaryKey() public method
Deprecated since 2.1.0

Alias to set_id(). Sets the primary key value.

public void setPrimaryKey ( $value )
$value mixed
throws \yii\base\InvalidCallException

when record is not new

                public function setPrimaryKey($value)
{
    $pk = static::primaryKey()[0];
    $this->$pk = $value;
}

            
set_id() public method

Sets the _id attribute that holds the primary key (for compatibility with relations)

public void set_id ( $value )
$value mixed
throws \yii\base\InvalidCallException

when record is not new

                public function set_id($value)
{
    $pk = static::primaryKey()[0];
    if ($this->getIsNewRecord()) {
        $this->$pk = $value;
    } else {
        throw new InvalidCallException('Changing the primaryKey of an already saved record is not allowed.');
    }
}

            
type() public static method

Returns the name of the type of this record.

IMPORTANT: For Elasticsearch 7 and later, type() is ignored.

public static string type ( )
return string

The name of the type of this record.

                public static function type()
{
    return Inflector::camel2id(StringHelper::basename(get_called_class()), '-');
}

            
unlinkAll() public method

Destroys the relationship in current model.

This method is not supported by Elasticsearch.

public void unlinkAll ( $name, $delete false )
$name
$delete

                public function unlinkAll($name, $delete = false)
{
    throw new NotSupportedException('unlinkAll() is not supported by Elasticsearch, use unlink() instead.');
}

            
update() public method

public integer|boolean update ( $runValidation true, $attributeNames null, $options = [] )
$runValidation boolean

Whether to perform validation before saving the record. If the validation fails, the record will not be inserted into the database.

$attributeNames array

List of attribute names that need to be saved. Defaults to null, meaning all attributes that are loaded from DB will be saved.

$options array

Options given in this parameter are passed to Elasticsearch as request URI parameters. These are among others:

  • routing define shard placement of this record.
  • parent by giving the primaryKey of another record this defines a parent-child relation
  • timeout timeout waiting for a shard to become available.
  • replication the replication type for the delete/index operation (sync or async).
  • consistency the write consistency of the index/delete operation.
  • refresh refresh the relevant primary and replica shards (not the whole index) immediately after the operation occurs, so that the updated document appears in search results immediately.
  • detect_noop this parameter will become part of the request body and will prevent the index from getting updated when nothing has changed.

Please refer to the Elasticsearch documentation for more details on these options.

The following parameters are Yii specific:

  • optimistic_locking set this to true to enable optimistic locking, avoid updating when the record has changed since it has been loaded from the database. Yii will set the version parameter to the value stored in version. See the Elasticsearch documentation for details.

    Make sure the record has been fetched with a version before. This is only the case for records fetched via get() and mget() by default. For normal queries, the _version field has to be fetched explicitly.

return integer|boolean

The number of rows affected, or false if validation fails or beforeSave() stops the updating process.

throws \yii\db\StaleObjectException

if optimistic locking is enabled and the data being updated is outdated.

throws \yii\elasticsearch\InvalidParamException

if no version is available and optimistic locking is enabled.

throws yii\elasticsearch\Exception

in case update failed.

                public function update($runValidation = true, $attributeNames = null, $options = [])
{
    if ($runValidation && !$this->validate($attributeNames)) {
        return false;
    }
    return $this->updateInternal($attributeNames, $options);
}

            
updateAll() public static method

Updates all records that match a certain condition.

For example, to change the status to be 1 for all customers whose status is 2:

Customer::updateAll(['status' => 1], ['status' => 2]);
public static integer updateAll ( $attributes, $condition = [] )
$attributes array

Attribute values (name-value pairs) to be saved into the table

$condition array

The conditions that will be passed to the where() method when building the query. Please refer to ActiveQuery::where() on how to specify this parameter.

return integer

The number of rows updated

throws yii\elasticsearch\Exception

on error.

                public static function updateAll($attributes, $condition = [])
{
    $primaryKeys = static::primaryKeysByCondition($condition);
    if (empty($primaryKeys)) {
        return 0;
    }
    $bulkCommand = static::getDb()->createBulkCommand([
        "index" => static::index(),
        "type" => static::type(),
    ]);
    foreach ($primaryKeys as $pk) {
        $bulkCommand->addAction(["update" => ["_id" => $pk]], ["doc" => $attributes]);
    }
    $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.', $errors);
    }
    return $n;
}

            
updateAllCounters() public static method

Updates all matching records using the provided counter changes and conditions.

For example, to add 1 to age of all customers whose status is 2,

Customer::updateAllCounters(['age' => 1], ['status' => 2]);
public static integer updateAllCounters ( $counters, $condition = [] )
$counters array

The counters to be updated (attribute name => increment value). Use negative values if you want to decrement the counters.

$condition array

The conditions that will be passed to the where() method when building the query. Please refer to ActiveQuery::where() on how to specify this parameter.

return integer

The number of rows updated

throws yii\elasticsearch\Exception

on error.

                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} += params.{$counter};\n";
        }
        $bulkCommand->addAction(["update" => ["_id" => $pk]], [
            'script' => [
                'inline' => $script,
                'params' => $counters,
                'lang' => 'painless',
            ],
        ]);
    }
    $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;
}

            
updateInternal() protected method

See also update().

protected integer|false updateInternal ( $attributes null, $options = [] )
$attributes array

Attributes to update

$options array

Options given in this parameter are passed to Elasticsearch as request URI parameters. See update() for details.

return integer|false

The number of rows affected, or false if beforeSave() stops the updating process.

throws \yii\db\StaleObjectException

if optimistic locking is enabled and the data being updated is outdated.

throws \yii\elasticsearch\InvalidParamException

if no version is available and optimistic locking is enabled.

throws yii\elasticsearch\Exception

in case update failed.

                protected function updateInternal($attributes = null, $options = [])
{
    if (!$this->beforeSave(false)) {
        return false;
    }
    $values = $this->getDirtyAttributes($attributes);
    if (empty($values)) {
        $this->afterSave(false, $values);
        return 0;
    }
    if (isset($options['optimistic_locking']) && $options['optimistic_locking']) {
        if ($this->_version === null) {
            throw new InvalidArgumentException('Unable to use optimistic locking on a record that has no version set. Refer to the docs of ActiveRecord::update() for details.');
        }
        $options['version'] = $this->_version;
        unset($options['optimistic_locking']);
    }
    try {
        $result = static::getDb()->createCommand()->update(
            static::index(),
            static::type(),
            $this->getOldPrimaryKey(false),
            $values,
            $options
        );
    } catch (Exception $e) {
        // HTTP 409 is the response in case of failed optimistic locking
        // https://www.elastic.co/guide/en/elasticsearch/guide/current/optimistic-concurrency-control.html
        if (isset($e->errorInfo['responseCode']) && $e->errorInfo['responseCode'] == 409) {
            throw new StaleObjectException('The object being updated is outdated.', $e->errorInfo, $e->getCode(), $e);
        }
        throw $e;
    }
    if (is_array($result) && isset($result['_version'])) {
        $this->_version = $result['_version'];
    }
    $changedAttributes = [];
    foreach ($values as $name => $value) {
        $changedAttributes[$name] = $this->getOldAttribute($name);
        $this->setOldAttribute($name, $value);
    }
    $this->afterSave(false, $changedAttributes);
    if ($result === false) {
        return 0;
    } else {
        return 1;
    }
}

            
validateViaRelationLink() protected method

Validates model so that it does not contain array as its keys while linking.

protected void validateViaRelationLink ( $model, $relation )
$model \yii\db\ActiveRecordInterface

The model to be linked with the current one.

$relation