Class yii\elasticsearch\ActiveRecord

Inheritanceyii\elasticsearch\ActiveRecord » yii\db\BaseActiveRecord
Available since version2.0

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. The primary key (the _id field in elasticsearch terms) is represented by getId() and setId(). The primary key is not part of the attributes.

The following is an example model called Customer:

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

You may override index() and type() to define the index and type this record represents.

Public Methods

Hide inherited methods

MethodDescriptionDefined 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() yii\elasticsearch\ActiveRecord
getScore() 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
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() Sets the primary key yii\elasticsearch\ActiveRecord
type() yii\elasticsearch\ActiveRecord
unlinkAll() Destroys the relationship in current model. yii\elasticsearch\ActiveRecord
update() yii\elasticsearch\ActiveRecord
updateAll() Updates all records whos primary keys are given. yii\elasticsearch\ActiveRecord
updateAllCounters() Updates all matching records using the provided counter changes and conditions. yii\elasticsearch\ActiveRecord

Protected Methods

Hide inherited methods

MethodDescriptionDefined 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

Method Details

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().

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.

Attributes are names of fields of the corresponding elasticsearch document. The primaryKey for elasticsearch documents is the _id field by default which is not part of the attributes. You may define path mapping for the _id field so that it is part of the _source fields and thus becomes part of the attributes.

public string[] attributes ( )
return string[]

List of attribute names.

throws \yii\base\InvalidConfigException

if not overridden in a child class.

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 \yii\elasticsearch\version. See the elasticsearch documentation for details.

    Make sure the record has been fetched with a \yii\elasticsearch\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.

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]);

See also [[yii\elasticsearch\ActiveRecord::primaryKeysByCondition()]].

public static integer deleteAll ( $condition = [] )
$condition array

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

return integer

The number of rows deleted

throws yii\elasticsearch\Exception

on error.

find() public static method

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

The newly created yii\elasticsearch\ActiveQuery instance.

findAll() public static method

public static void findAll ( $condition )
$condition
findOne() public static method

public static void findOne ( $condition )
$condition
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 static|null

The record instance or null if it was not found.

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.

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.

getHighlight() public method

public array|null getHighlight ( )
return array|null

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

getOldPrimaryKey() public method

public void getOldPrimaryKey ( $asArray false )
$asArray
getPrimaryKey() public method

public void getPrimaryKey ( $asArray false )
$asArray
getScore() public method

public float getScore ( )
return float

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

index() public static method

public static string index ( )
return string

The name of the index this record is stored in.

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 \yii\elasticsearch\beforeValidate() when $runValidation is true. If validation fails, it will skip the rest of the steps;
  2. call \yii\elasticsearch\afterValidate() when $runValidation is true.
  3. call \yii\elasticsearch\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 \yii\elasticsearch\afterSave();

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

Only the \yii\elasticsearch\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.

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 static

The newly created active record

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

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 ( )
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)

primaryKey() public static method

This method defines the attribute that uniquely identifies a record.

The primaryKey for elasticsearch documents is the _id field by default. This field is not part of the ActiveRecord attributes so you should never add _id to the list of attributes.

You may override this method to define the primary key name when you have defined path mapping for the _id field so that it is part of the _source and thus part of the attributes.

Note that elasticsearch only supports one attribute to be the primary key. 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.

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 yii\elasticsearch\ActiveQuery::where() on how to specify this parameter

return array

Primary keys that correspond to given conditions

setPrimaryKey() public method

Sets the primary key

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

when record is not new

type() public static method

public static string type ( )
return string

The name of the type of this record.

unlinkAll() public method

Destroys the relationship in current model.

This method is not supported by elasticsearch.

public void unlinkAll ( $name, $delete false )
$name
$delete
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 \yii\elasticsearch\version. See the elasticsearch documentation for details.

    Make sure the record has been fetched with a \yii\elasticsearch\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 \yii\elasticsearch\beforeSave() stops the updating process.

throws \yii\db\StaleObjectException

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

throws \yii\base\InvalidParamException

if no \yii\elasticsearch\version is available and optimistic locking is enabled.

throws yii\elasticsearch\Exception

in case update failed.

updateAll() public static method

Updates all records whos primary keys are given.

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

Customer::updateAll(['status' => 1], ['status' => 2]);

See also [[yii\elasticsearch\ActiveRecord::primaryKeysByCondition()]].

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 yii\elasticsearch\ActiveQuery::where() on how to specify this parameter.

return integer

The number of rows updated

throws yii\elasticsearch\Exception

on error.

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]);

See also [[yii\elasticsearch\ActiveRecord::primaryKeysByCondition()]].

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 yii\elasticsearch\ActiveQuery::where() on how to specify this parameter.

return integer

The number of rows updated

throws yii\elasticsearch\Exception

on error.

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 \yii\elasticsearch\beforeSave() stops the updating process.

throws \yii\db\StaleObjectException

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

throws \yii\base\InvalidParamException

if no \yii\elasticsearch\version is available and optimistic locking is enabled.

throws yii\elasticsearch\Exception

in case update failed.