Class yii\elasticsearch\ActiveQuery
Inheritance | yii\elasticsearch\ActiveQuery » yii\elasticsearch\Query » yii\base\Component |
---|---|
Implements | yii\db\ActiveQueryInterface, yii\db\QueryInterface |
Uses Traits | yii\db\ActiveQueryTrait, yii\db\ActiveRelationTrait, yii\db\QueryTrait |
Available since extension's version | 2.0 |
Source Code | https://github.com/yiisoft/yii2-elasticsearch/blob/master/ActiveQuery.php |
ActiveQuery represents a yii\elasticsearch\Query associated with an yii\elasticsearch\ActiveRecord class.
An ActiveQuery can be a normal query or be used in a relational context.
ActiveQuery instances are usually created by yii\elasticsearch\ActiveRecord::find(). Relational queries are created by ActiveRecord::hasOne() and ActiveRecord::hasMany().
Normal Query ¶
ActiveQuery mainly provides the following methods to retrieve the query results:
- one(): returns a single record populated with the first row of data.
- all(): returns all records based on the query results.
- count(): returns the number of records.
- scalar(): returns the value of the first column in the first row of the query result.
- column(): returns the value of the first column in the query result.
- exists(): returns a value indicating whether the query result has data or not.
Because ActiveQuery extends from yii\elasticsearch\Query, one can use query methods, such as where(), orderBy() to customize the query options.
ActiveQuery also provides the following additional query options:
- with(): list of relations that this query should be performed with.
- indexBy(): the name of the column by which the query result should be indexed.
- asArray(): whether to return each record as an array.
These options can be configured using methods of the same name. For example:
$customers = Customer::find()->with('orders')->asArray()->all();
Note: elasticsearch limits the number of records returned to 10 records by default. If you expect to get more records you should specify limit explicitly.
Relational query ¶
In relational context ActiveQuery represents a relation between two Active Record classes.
Relational ActiveQuery instances are usually created by calling ActiveRecord::hasOne() and ActiveRecord::hasMany(). An Active Record class declares a relation by defining a getter method which calls one of the above methods and returns the created ActiveQuery object.
A relation is specified by link which represents the association between columns of different tables; and the multiplicity of the relation is indicated by multiple.
If a relation involves a junction table, it may be specified by via(). This methods may only be called in a relational context. Same is true for inverseOf(), which marks a relation as inverse of another relation.
Note: elasticsearch limits the number of records returned by any query to 10 records by default. If you expect to get more records you should specify limit explicitly in relation definition. This is also important for relations that use via() so that if via records are limited to 10 the relations records can also not be more than 10.
Note: Currently with is not supported in combination with asArray.
Public Properties
Property | Type | Description | Defined By |
---|---|---|---|
$aggregations | array | List of aggregations to add to this query. | yii\elasticsearch\Query |
$explain | boolean | Enables explanation for each hit on how its score was computed. | yii\elasticsearch\Query |
$fields | array | The fields being retrieved from the documents. | yii\elasticsearch\Query |
$filter | array|string | The filter part of this search query. | yii\elasticsearch\Query |
$highlight | array | The highlight part of this search query. | yii\elasticsearch\Query |
$index | string|array | The index to retrieve data from. | yii\elasticsearch\Query |
$minScore | float | Exclude documents which have a _score less than the minimum specified in min_score | yii\elasticsearch\Query |
$options | array | List of options that will passed to commands created by this query. | yii\elasticsearch\Query |
$postFilter | string|array | The post_filter part of the search query for differentially filter search results and aggregations. |
yii\elasticsearch\Query |
$query | array|string | The query part of this search query. | yii\elasticsearch\Query |
$source | array | This option controls how the _source field is returned from the documents. |
yii\elasticsearch\Query |
$stats | array | The 'stats' part of the query. | yii\elasticsearch\Query |
$suggest | array | List of suggesters to add to this query. | yii\elasticsearch\Query |
$timeout | integer | A search timeout, bounding the search request to be executed within the specified time value and bail with the hits accumulated up to that point when expired. | yii\elasticsearch\Query |
$type | string|array | The type to retrieve data from. | yii\elasticsearch\Query |
Public Methods
Method | Description | Defined By |
---|---|---|
__construct() | Constructor. | yii\elasticsearch\ActiveQuery |
addAgg() | yii\elasticsearch\Query | |
addAggregate() | Adds an aggregation to this query. Supports nested aggregations. | yii\elasticsearch\Query |
addAggregation() | yii\elasticsearch\Query | |
addOptions() | Adds more options, overwriting existing options. | yii\elasticsearch\Query |
addSuggester() | Adds a suggester to this query. | yii\elasticsearch\Query |
all() | Executes query and returns all results as an array. | yii\elasticsearch\ActiveQuery |
batch() | Starts a batch query. | yii\elasticsearch\Query |
column() | Executes the query and returns the first column of the result. | yii\elasticsearch\ActiveQuery |
count() | Returns the number of records. | yii\elasticsearch\Query |
createCommand() | Creates a DB command that can be used to execute this query. | yii\elasticsearch\ActiveQuery |
delete() | Executes the query and deletes all matching documents. | yii\elasticsearch\Query |
each() | Starts a batch query and retrieves data row by row. | yii\elasticsearch\Query |
exists() | Returns a value indicating whether the query result contains any row of data. | yii\elasticsearch\Query |
explain() | Explain for how the score of each document was computer | yii\elasticsearch\Query |
fields() | Sets the fields to retrieve from the documents. | yii\elasticsearch\Query |
filter() | Sets the filter part of this search query. | yii\elasticsearch\Query |
from() | Sets the index and type to retrieve documents from. | yii\elasticsearch\Query |
highlight() | Sets a highlight parameters to retrieve from the documents. | yii\elasticsearch\Query |
init() | Initializes the object. | yii\elasticsearch\ActiveQuery |
minScore() | yii\elasticsearch\Query | |
one() | Executes query and returns a single row of result. | yii\elasticsearch\ActiveQuery |
options() | Sets the options to be passed to the command created by this query. | yii\elasticsearch\Query |
populate() | Converts the raw query results into the format as specified by this query. | yii\elasticsearch\ActiveQuery |
postFilter() | Set the post_filter part of the search query. |
yii\elasticsearch\Query |
query() | Sets the query part of this search query. | yii\elasticsearch\Query |
scalar() | Returns the query result as a scalar value. | yii\elasticsearch\Query |
search() | Executes the query and returns the complete search result including e.g. hits, facets, totalCount. | yii\elasticsearch\ActiveQuery |
source() | Sets the source filtering, specifying how the _source field of the document should be returned. |
yii\elasticsearch\Query |
stats() | Adds a 'stats' part to the query. | yii\elasticsearch\Query |
timeout() | Sets the search timeout. | yii\elasticsearch\Query |
Events
Event | Type | Description | Defined By |
---|---|---|---|
EVENT_INIT | yii\elasticsearch\Event | An event that is triggered when the query is initialized via init(). | yii\elasticsearch\ActiveQuery |
Method Details
Constructor.
public void __construct ( $modelClass, $config = [] ) | ||
$modelClass | array |
The model class associated with this query |
$config | array |
Configurations to be applied to the newly created query object |
public function __construct($modelClass, $config = [])
{
$this->modelClass = $modelClass;
parent::__construct($config);
}
Defined in: yii\elasticsearch\Query::addAgg()
See also http://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations.html.
public $this addAgg ( $name, $type, $options ) | ||
$name | string |
The name of the aggregation |
$type | string |
The aggregation type. e.g. |
$options | string|array |
The configuration options for this aggregation. Can be an array or a json string. |
return | $this |
The query object itself |
---|
public function addAgg($name, $type, $options)
{
return $this->addAggregate($name, [$type => $options]);
}
Defined in: yii\elasticsearch\Query::addAggregate()
Adds an aggregation to this query. Supports nested aggregations.
See also https://www.elastic.co/guide/en/elasticsearch/reference/2.3/search-aggregations.html.
public $this addAggregate ( $name, $options ) | ||
$name | string |
The name of the aggregation |
$options | string|array |
The configuration options for this aggregation. Can be an array or a json string. |
return | $this |
The query object itself |
---|
public function addAggregate($name, $options)
{
$this->aggregations[$name] = $options;
return $this;
}
Defined in: yii\elasticsearch\Query::addAggregation()
See also http://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations.html.
public $this addAggregation ( $name, $type, $options ) | ||
$name | string |
The name of the aggregation |
$type | string |
The aggregation type. e.g. |
$options | string|array |
The configuration options for this aggregation. Can be an array or a json string. |
return | $this |
The query object itself |
---|
public function addAggregation($name, $type, $options)
{
return $this->addAggregate($name, [$type => $options]);
}
Defined in: yii\elasticsearch\Query::addOptions()
Adds more options, overwriting existing options.
See also options().
public $this addOptions ( $options ) | ||
$options | array |
The options to be added. |
return | $this |
The query object itself |
---|---|---|
throws | \yii\base\InvalidParamException |
if $options is not an array |
public function addOptions($options)
{
if (!is_array($options)) {
throw new InvalidParamException('Array parameter expected, ' . gettype($options) . ' received.');
}
$this->options = array_merge($this->options, $options);
return $this;
}
Defined in: yii\elasticsearch\Query::addSuggester()
Adds a suggester to this query.
See also http://www.elastic.co/guide/en/elasticsearch/reference/current/search-suggesters.html.
public $this addSuggester ( $name, $definition ) | ||
$name | string |
The name of the suggester |
$definition | string|array |
The configuration options for this suggester. Can be an array or a json string. |
return | $this |
The query object itself |
---|
public function addSuggester($name, $definition)
{
$this->suggest[$name] = $definition;
return $this;
}
Executes query and returns all results as an array.
public array all ( $db = null ) | ||
$db | yii\elasticsearch\Connection |
The DB connection used to create the DB command. If null, the DB connection returned by modelClass will be used. |
return | array |
The query results. If the query results in nothing, an empty array will be returned. |
---|
public function all($db = null)
{
return parent::all($db);
}
Defined in: yii\elasticsearch\Query::batch()
Starts a batch query.
A batch query supports fetching data in batches, which can keep the memory usage under a limit. This method will return a yii\elasticsearch\BatchQueryResult object which implements the Iterator interface and can be traversed to retrieve the data in batches.
For example,
$query = (new Query)->from('user');
foreach ($query->batch() as $rows) {
// $rows is an array of 10 or fewer rows from user table
}
Batch size is determined by the limit
setting (note that in scan mode batch limit is per shard).
public yii\elasticsearch\BatchQueryResult batch ( $scrollWindow = '1m', $db = null ) | ||
$scrollWindow | string |
How long Elasticsearch should keep the search context alive, in time units |
$db | yii\elasticsearch\Connection |
The database connection. If not set, the |
return | yii\elasticsearch\BatchQueryResult |
The batch query result. It implements the Iterator interface and can be traversed to retrieve the data in batches. |
---|
public function batch($scrollWindow = '1m', $db = null)
{
return Yii::createObject([
'class' => BatchQueryResult::className(),
'query' => $this,
'scrollWindow' => $scrollWindow,
'db' => $db,
'each' => false,
]);
}
Executes the query and returns the first column of the result.
public array column ( $field, $db = null ) | ||
$field | string |
The field to query over |
$db | yii\elasticsearch\Connection |
The database connection used to execute the query.
If this parameter is not given, the |
return | array |
The first column of the query result. An empty array is returned if the query results in nothing. |
---|
public function column($field, $db = null)
{
if ($field == '_id') {
$command = $this->createCommand($db);
$command->queryParts['fields'] = [];
$command->queryParts['_source'] = false;
$result = $command->search();
if (empty($result['hits']['hits'])) {
return [];
}
$column = [];
foreach ($result['hits']['hits'] as $row) {
$column[] = $row['_id'];
}
return $column;
}
return parent::column($field, $db);
}
Defined in: yii\elasticsearch\Query::count()
Returns the number of records.
public integer count ( $q = '*', $db = null ) | ||
$q | string |
The COUNT expression. This parameter is ignored by this implementation. |
$db | yii\elasticsearch\Connection |
The database connection used to execute the query.
If this parameter is not given, the |
return | integer |
Number of records |
---|
public function count($q = '*', $db = null)
{
if ($this->emulateExecution) {
return 0;
}
// TODO consider sending to _count api instead of _search for performance
// only when no facety are registerted.
// http://www.elastic.co/guide/en/elasticsearch/reference/current/search-count.html
// http://www.elastic.co/guide/en/elasticsearch/reference/1.x/_search_requests.html
$options = [];
$options['search_type'] = 'count';
return $this->createCommand($db)->search($options)['hits']['total'];
}
Creates a DB command that can be used to execute this query.
public yii\elasticsearch\Command createCommand ( $db = null ) | ||
$db | yii\elasticsearch\Connection |
The DB connection used to create the DB command. If null, the DB connection returned by modelClass will be used. |
return | yii\elasticsearch\Command |
The created DB command instance. |
---|
public function createCommand($db = null)
{
if ($this->primaryModel !== null) {
// lazy loading
if (is_array($this->via)) {
// via relation
/* @var $viaQuery ActiveQuery */
list($viaName, $viaQuery) = $this->via;
if ($viaQuery->multiple) {
$viaModels = $viaQuery->all();
$this->primaryModel->populateRelation($viaName, $viaModels);
} else {
$model = $viaQuery->one();
$this->primaryModel->populateRelation($viaName, $model);
$viaModels = $model === null ? [] : [$model];
}
$this->filterByModels($viaModels);
} else {
$this->filterByModels([$this->primaryModel]);
}
}
/* @var $modelClass ActiveRecord */
$modelClass = $this->modelClass;
if ($db === null) {
$db = $modelClass::getDb();
}
if ($this->type === null) {
$this->type = $modelClass::type();
}
if ($this->index === null) {
$this->index = $modelClass::index();
$this->type = $modelClass::type();
}
$commandConfig = $db->getQueryBuilder()->build($this);
return $db->createCommand($commandConfig);
}
Defined in: yii\elasticsearch\Query::delete()
Executes the query and deletes all matching documents.
Everything except query and filter will be ignored.
public array delete ( $db = null, $options = [] ) | ||
$db | yii\elasticsearch\Connection |
The database connection used to execute the query.
If this parameter is not given, the |
$options | array |
The options given with this query. |
return | array |
The query results. |
---|
public function delete($db = null, $options = [])
{
if ($this->emulateExecution) {
return [];
}
return $this->createCommand($db)->deleteByQuery($options);
}
Defined in: yii\elasticsearch\Query::each()
Starts a batch query and retrieves data row by row.
This method is similar to batch() except that in each iteration of the result, only one row of data is returned. For example,
$query = (new Query)->from('user');
foreach ($query->each() as $row) {
}
public yii\elasticsearch\BatchQueryResult each ( $scrollWindow = '1m', $db = null ) | ||
$scrollWindow | string |
How long Elasticsearch should keep the search context alive, in time units |
$db | yii\elasticsearch\Connection |
The database connection. If not set, the |
return | yii\elasticsearch\BatchQueryResult |
The batch query result. It implements the Iterator interface and can be traversed to retrieve the data in batches. |
---|
public function each($scrollWindow = '1m', $db = null)
{
return Yii::createObject([
'class' => BatchQueryResult::className(),
'query' => $this,
'scrollWindow' => $scrollWindow,
'db' => $db,
'each' => true,
]);
}
Defined in: yii\elasticsearch\Query::exists()
Returns a value indicating whether the query result contains any row of data.
public boolean exists ( $db = null ) | ||
$db | yii\elasticsearch\Connection |
The database connection used to execute the query.
If this parameter is not given, the |
return | boolean |
Whether the query result contains any row of data. |
---|
public function exists($db = null)
{
return self::one($db) !== false;
}
Defined in: yii\elasticsearch\Query::explain()
Explain for how the score of each document was computer
public $this explain ( $explain ) | ||
$explain |
public function explain($explain)
{
$this->explain = $explain;
return $this;
}
Defined in: yii\elasticsearch\Query::fields()
Sets the fields to retrieve from the documents.
See also http://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-fields.html.
public $this fields ( $fields ) | ||
$fields | array |
The fields to be selected. |
return | $this |
The query object itself |
---|
public function fields($fields)
{
if (is_array($fields) || $fields === null) {
$this->fields = $fields;
} else {
$this->fields = func_get_args();
}
return $this;
}
Defined in: yii\elasticsearch\Query::filter()
Sets the filter part of this search query.
public $this filter ( $filter ) | ||
$filter | string | |
return | $this |
The query object itself |
---|
public function filter($filter)
{
$this->filter = $filter;
return $this;
}
Defined in: yii\elasticsearch\Query::from()
Sets the index and type to retrieve documents from.
public $this from ( $index, $type = null ) | ||
$index | string|array |
The index to retrieve data from. This can be a string representing a single index
or a an array of multiple indexes. If this is |
$type | string|array |
The type to retrieve data from. This can be a string representing a single type
or a an array of multiple types. If this is |
return | $this |
The query object itself |
---|
public function from($index, $type = null)
{
$this->index = $index;
$this->type = $type;
return $this;
}
Defined in: yii\elasticsearch\Query::highlight()
Sets a highlight parameters to retrieve from the documents.
See also http://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-highlighting.html.
public $this highlight ( $highlight ) | ||
$highlight | array |
Array of parameters to highlight results. |
return | $this |
The query object itself |
---|
public function highlight($highlight)
{
$this->highlight = $highlight;
return $this;
}
Initializes the object.
This method is called at the end of the constructor. The default implementation will trigger an EVENT_INIT event. If you override this method, make sure you call the parent implementation at the end to ensure triggering of the event.
public void init ( ) |
public function init()
{
parent::init();
$this->trigger(self::EVENT_INIT);
}
Defined in: yii\elasticsearch\Query::minScore()
See also http://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-min-score.html.
public static minScore ( $minScore ) | ||
$minScore | float |
Exclude documents which have a |
return | yii\elasticsearch\Query |
The query object itself |
---|
public function minScore($minScore)
{
$this->minScore = $minScore;
return $this;
}
Executes query and returns a single row of result.
public yii\elasticsearch\ActiveRecord|array|null one ( $db = null ) | ||
$db | yii\elasticsearch\Connection |
The DB connection used to create the DB command. If null, the DB connection returned by modelClass will be used. |
return | yii\elasticsearch\ActiveRecord|array|null |
A single row of query result. Depending on the setting of asArray, the query result may be either an array or an ActiveRecord object. Null will be returned if the query results in nothing. |
---|
public function one($db = null)
{
if (($result = parent::one($db)) === false) {
return null;
}
if ($this->asArray) {
// TODO implement with()
/* @var $modelClass ActiveRecord */
$modelClass = $this->modelClass;
$model = $result['_source'];
$pk = $modelClass::primaryKey()[0];
if ($pk === '_id') {
$model['_id'] = $result['_id'];
}
$model['_score'] = $result['_score'];
if (!empty($this->with)) {
$models = [$model];
$this->findWith($this->with, $models);
$model = $models[0];
}
return $result;
} else {
/* @var $class ActiveRecord */
$class = $this->modelClass;
$model = $class::instantiate($result);
$class = get_class($model);
$class::populateRecord($model, $result);
if (!empty($this->with)) {
$models = [$model];
$this->findWith($this->with, $models);
$model = $models[0];
}
$model->afterFind();
return $model;
}
}
Defined in: yii\elasticsearch\Query::options()
Sets the options to be passed to the command created by this query.
See also yii\elasticsearch\Command::$options.
public $this options ( $options ) | ||
$options | array |
The options to be set. |
return | $this |
The query object itself |
---|---|---|
throws | \yii\base\InvalidParamException |
if $options is not an array |
public function options($options)
{
if (!is_array($options)) {
throw new InvalidParamException('Array parameter expected, ' . gettype($options) . ' received.');
}
$this->options = $options;
return $this;
}
Converts the raw query results into the format as specified by this query.
This method is internally used to convert the data fetched from database into the format as required by this query.
public array populate ( $rows ) | ||
$rows | array |
The raw query result from database |
return | array |
The converted query result |
---|
public function populate($rows)
{
if (empty($rows)) {
return [];
}
$models = $this->createModels($rows);
if (!empty($this->with)) {
$this->findWith($this->with, $models);
}
if (!$this->asArray) {
foreach ($models as $model) {
$model->afterFind();
}
}
return $models;
}
Defined in: yii\elasticsearch\Query::postFilter()
Set the post_filter
part of the search query.
public $this postFilter ( $filter ) | ||
$filter | string|array | |
return | $this |
The query object itself |
---|
public function postFilter($filter)
{
$this->postFilter = $filter;
return $this;
}
Defined in: yii\elasticsearch\Query::query()
Sets the query part of this search query.
public $this query ( $query ) | ||
$query | string|array | |
return | $this |
The query object itself |
---|
public function query($query)
{
$this->query = $query;
return $this;
}
Defined in: yii\elasticsearch\Query::scalar()
Returns the query result as a scalar value.
The value returned will be the specified field in the first document of the query results.
public string scalar ( $field, $db = null ) | ||
$field | string |
Name of the attribute to select |
$db | yii\elasticsearch\Connection |
The database connection used to execute the query.
If this parameter is not given, the |
return | string |
The value of the specified attribute in the first record of the query result. Null is returned if the query result is empty or the field does not exist. |
---|
public function scalar($field, $db = null)
{
if ($this->emulateExecution) {
return null;
}
$record = self::one($db);
if ($record !== false) {
if ($field === '_id') {
return $record['_id'];
} elseif (isset($record['_source'][$field])) {
return $record['_source'][$field];
} elseif (isset($record['fields'][$field])) {
return count($record['fields'][$field]) == 1 ? reset($record['fields'][$field]) : $record['fields'][$field];
}
}
return null;
}
Executes the query and returns the complete search result including e.g. hits, facets, totalCount.
public array search ( $db = null, $options = [] ) | ||
$db | yii\elasticsearch\Connection |
The database connection used to execute the query.
If this parameter is not given, the |
$options | array |
The options given with this query. Possible options are: |
return | array |
The query results. |
---|
public function search($db = null, $options = [])
{
if ($this->emulateExecution) {
return [
'hits' => [
'total' => 0,
'hits' => [],
],
];
}
$result = $this->createCommand($db)->search($options);
// TODO implement with() for asArray
if (!empty($result['hits']['hits']) && !$this->asArray) {
$models = $this->createModels($result['hits']['hits']);
if (!empty($this->with)) {
$this->findWith($this->with, $models);
}
foreach ($models as $model) {
$model->afterFind();
}
$result['hits']['hits'] = $models;
}
return $result;
}
Defined in: yii\elasticsearch\Query::source()
Sets the source filtering, specifying how the _source
field of the document should be returned.
See also http://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-source-filtering.html.
public $this source ( $source ) | ||
$source | array |
The source patterns to be selected. |
return | $this |
The query object itself |
---|
public function source($source)
{
if (is_array($source) || $source === null) {
$this->source = $source;
} else {
$this->source = func_get_args();
}
return $this;
}
Defined in: yii\elasticsearch\Query::stats()
Adds a 'stats' part to the query.
See also http://www.elastic.co/guide/en/elasticsearch/reference/current/search.html#stats-groups.
public $this stats ( $groups ) | ||
$groups | array |
An array of groups to maintain a statistics aggregation for. |
return | $this |
The query object itself |
---|
public function stats($groups)
{
$this->stats = $groups;
return $this;
}
Defined in: yii\elasticsearch\Query::timeout()
Sets the search timeout.
public $this timeout ( $timeout ) | ||
$timeout | integer |
A search timeout, bounding the search request to be executed within the specified time value and bail with the hits accumulated up to that point when expired. Defaults to no timeout. |
return | $this |
The query object itself |
---|
public function timeout($timeout)
{
$this->timeout = $timeout;
return $this;
}
Event Details
An event that is triggered when the query is initialized via init().