PHP Class yii\elasticsearch\ActiveRecord

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 ActiveRecord::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: php class Customer extends \yii\elasticsearch\ActiveRecord { public function attributes() { return ['id', 'name', 'address', 'registration_date']; } } You may override ActiveRecord::index and ActiveRecord::type to define the index and type this record represents.
Since: 2.0
Author: Carsten Brandt ([email protected])
Inheritance: extends yii\db\BaseActiveRecord
Datei anzeigen Open project: yiisoft/yii2-elasticsearch Class Usage Examples

Public Methods

Method Description
arrayAttributes ( ) : string[] A list of attributes that should be treated as array valued when retrieved through [[ActiveQuery::fields]].
attributes ( ) : string[] Returns the list of all attribute names of the model.
delete ( array $options = [] ) : integer | boolean
deleteAll ( array $condition = [] ) : integer Deletes rows in the table using the provided conditions.
find ( ) : ActiveQuery
findAll ( $condition )
findOne ( $condition )
get ( mixed $primaryKey, array $options = [] ) : static | null Gets a record by its primary key.
getDb ( ) : Connection Returns the database connection used by this AR class.
getHighlight ( ) : array | null
getOldPrimaryKey ( $asArray = false )
getPrimaryKey ( $asArray = false )
getScore ( ) : float
index ( ) : string
insert ( boolean $runValidation = true, array $attributes = null, array $options = ['op_type' => 'create'] ) : boolean Inserts a document into the associated index using the attribute values of this record.
instantiate ( array $row ) : static Creates an active record instance.
mget ( array $primaryKeys, array $options = [] ) : array Gets a list of records by its primary keys.
optimisticLock ( ) This method has no effect in Elasticsearch ActiveRecord.
populateRecord ( ActiveRecord $record, array $row )
primaryKey ( ) : string[] This method defines the attribute that uniquely identifies a record.
setPrimaryKey ( mixed $value ) Sets the primary key
type ( ) : string
unlinkAll ( $name, $delete = false ) Destroys the relationship in current model.
update ( boolean $runValidation = true, array $attributeNames = null, array $options = [] ) : integer | boolean
updateAll ( array $attributes, array $condition = [] ) : integer Updates all records whos primary keys are given.
updateAllCounters ( array $counters, array $condition = [] ) : integer Updates all matching records using the provided counter changes and conditions.

Protected Methods

Method Description
primaryKeysByCondition ( array $condition ) : array 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.
updateInternal ( array $attributes = null, array $options = [] ) : integer | false

Method Details

arrayAttributes() public method

If not listed by this method, attributes retrieved through [[ActiveQuery::fields]] will converted to a scalar value when the result array contains only one value.
public arrayAttributes ( ) : string[]
return string[] list of attribute names. Must be a subset of [[attributes()]].

attributes() public method

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 attributes ( ) : string[]
return string[] list of attribute names.

delete() public method

public delete ( array $options = [] ) : integer | boolean
$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](http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-delete.html) 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](http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-delete.html#delete-versioning) 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.

deleteAll() public static method

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 deleteAll ( array $condition = [] ) : integer
$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

find() public static method

public static find ( ) : ActiveQuery
return ActiveQuery the newly created [[ActiveQuery]] instance.

findAll() public static method

public static findAll ( $condition )

findOne() public static method

public static findOne ( $condition )

get() public static method

Gets a record by its primary key.
public static get ( mixed $primaryKey, array $options = [] ) : static | null
$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](http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-get.html) for more details on these options.
return static | null The record instance or null if it was not found.

getDb() public static method

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 getDb ( ) : Connection
return Connection the database connection used by this AR class.

getHighlight() public method

public getHighlight ( ) : array | null
return array | null A list of arrays with highlighted excerpts indexed by field names.

getOldPrimaryKey() public method

public getOldPrimaryKey ( $asArray = false )

getPrimaryKey() public method

public getPrimaryKey ( $asArray = false )

getScore() public method

public getScore ( ) : float
return float returns the score of this record when it was retrieved via a [[find()]] query.

index() public static method

public static index ( ) : string
return string the name of the index this record is stored in.

insert() public method

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|changed attribute values]] will be inserted into database. If the [[primaryKey|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 insert ( boolean $runValidation = true, array $attributes = null, array $options = ['op_type' => 'create'] ) : boolean
$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 - `timestamp` specifies the timestamp to store along with the document. Default is indexing time. Please refer to the [elasticsearch documentation](http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-index_.html) for more details on these options. By default the `op_type` is set to `create`.
return boolean whether the attributes are valid and the record is inserted successfully.

instantiate() public static method

This method is called together with ActiveRecord::populateRecord by 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 instantiate ( array $row ) : static
$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 mget ( array $primaryKeys, array $options = [] ) : array
$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](http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-get.html) for more details on these options.
return array The record instances, or empty array if nothing was found

optimisticLock() public method

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

populateRecord() public static method

public static populateRecord ( ActiveRecord $record, array $row )
$record 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

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()|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()|attributes]]. Note that elasticsearch only supports _one_ attribute to be the primary key. However to match the signature of the [[\yii\db\ActiveRecordInterface|ActiveRecordInterface]] this methods returns an array instead of a single string.
public static primaryKey ( ) : string[]
return string[] array of primary key attributes. Only the first element of the array will be used.

primaryKeysByCondition() protected static method

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: updateAll()
See also: updateAllCounters()
See also: deleteAll()
Since: 2.0.4
protected static primaryKeysByCondition ( array $condition ) : array
$condition array please refer to [[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 setPrimaryKey ( mixed $value )
$value mixed

type() public static method

public static type ( ) : string
return string the name of the type of this record.

unlinkAll() public method

This method is not supported by elasticsearch.
public unlinkAll ( $name, $delete = false )

update() public method

public update ( boolean $runValidation = true, array $attributeNames = null, array $options = [] ) : integer | boolean
$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](http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-update.html#_parameters_3) 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](http://www.elastic.co/guide/en/elasticsearch/guide/current/optimistic-concurrency-control.html) 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.

updateAll() public static method

For example, to change the status to be 1 for all customers whose status is 2: ~~~ Customer::updateAll(['status' => 1], ['status' => 2]); ~~~
public static updateAll ( array $attributes, array $condition = [] ) : integer
$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

updateAllCounters() public static method

For example, to add 1 to age of all customers whose status is 2, ~~~ Customer::updateAllCounters(['age' => 1], ['status' => 2]); ~~~
public static updateAllCounters ( array $counters, array $condition = [] ) : integer
$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

updateInternal() protected method

See also: update()
protected updateInternal ( array $attributes = null, array $options = [] ) : integer | false
$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.