Class yii\elasticsearch\Query

Inheritanceyii\elasticsearch\Query » yii\base\Component
Implementsyii\db\QueryInterface
Uses Traitsyii\db\QueryTrait
Subclassesyii\elasticsearch\ActiveQuery
Available since extension's version2.0
Source Code https://github.com/yiisoft/yii2-elasticsearch/blob/master/Query.php

Query represents a query to the search API of Elasticsearch.

Query provides a set of methods to facilitate the specification of different parameters of the query. These methods can be chained together.

By calling createCommand(), we can get a yii\elasticsearch\Command instance which can be further used to perform/execute the DB query against a database.

For example,

$query = new Query;
$query->storedFields('id, name')
    ->from('myindex', 'users')
    ->limit(10);
// build and execute the query
$command = $query->createCommand();
$rows = $command->search(); // this way you get the raw output of Elasticsearch.

You would normally call $query->search() instead of creating a command as this method adds the indexBy() feature and also removes some inconsistencies from the response.

Query also provides some methods to easier get some parts of the result only:

  • 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.

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.

Public Properties

Hide inherited properties

Property Type Description Defined By
$aggregations array List of aggregations to add to this query. yii\elasticsearch\Query
$collapse array List of collapse 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 Use the fields parameter to retrieve the values of runtime fields. 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
$runtimeMappings array An array of runtime fields evaluated at query time Example: `php $query->$runtimeMappings = [ 'value_times_two' => [ 'type' => 'double', 'script' => "emit(doc['my_field_name'].value * 2)", ], 'value_times_factor' => [ 'type' => 'double', 'script' => "emit(doc['my_field_name'].value * factor)", 'params' => [ 'factor' => 2.0 ], ], ] ` yii\elasticsearch\Query
$scriptFields array The scripted fields being retrieved from the documents. 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
$storedFields array The fields being retrieved from the documents. 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

Hide inherited methods

Method Description Defined By
addAgg() yii\elasticsearch\Query
addAggregate() Adds an aggregation to this query. Supports nested aggregations. yii\elasticsearch\Query
addAggregation() yii\elasticsearch\Query
addCollapse() Adds a collapse to this query. 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 the query and returns all results as an array. yii\elasticsearch\Query
andWhere() yii\elasticsearch\Query
batch() Starts a batch query. yii\elasticsearch\Query
column() Executes the query and returns the first column of the result. yii\elasticsearch\Query
count() Returns the number of records. yii\elasticsearch\Query
createCommand() Creates a DB command that can be used to execute this query. yii\elasticsearch\Query
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 runtime fields to retrieve from the documents. 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() yii\elasticsearch\Query
minScore() yii\elasticsearch\Query
one() Executes the query and returns a single row of result. yii\elasticsearch\Query
options() Sets the options to be passed to the command created by this query. yii\elasticsearch\Query
orWhere() yii\elasticsearch\Query
populate() 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. yii\elasticsearch\Query
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
runtimeMappings() Sets the runtime mappings for this query 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. yii\elasticsearch\Query
scriptFields() Sets the script fields to retrieve from the documents. yii\elasticsearch\Query
search() Executes the query and returns the complete search result including e.g. yii\elasticsearch\Query
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
storedFields() Sets the fields to retrieve from the documents. yii\elasticsearch\Query
timeout() Sets the search timeout. yii\elasticsearch\Query

Property Details

Hide inherited properties

$aggregations public property
public array $aggregations = []
$collapse public property (available since version 2.1.0)
public array $collapse = []
$explain public property (available since version 2.0.5)

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

See also https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-explain.html.

public boolean $explain null
$fields public property

Use the fields parameter to retrieve the values of runtime fields. Runtime fields won’t display in _source, but the fields API works for all fields, even those that were not sent as part of the original _source.

See also:

public array $fields null
$filter public property

The filter part of this search query. This is an array or json string that follows the format of the elasticsearch Query DSL.

public array|string $filter null
$highlight public property

The highlight part of this search query. This is an array that allows to highlight search results on one or more fields.

See also https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-highlighting.html.

public array $highlight null
$index public property

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 not set, indexes are being queried.

See also from().

public string|array $index null
$minScore public property (available since version 2.0.4)

Exclude documents which have a _score less than the minimum specified in min_score

See also https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-min-score.html.

public float $minScore null
$options public property (available since version 2.0.4)

List of options that will passed to commands created by this query.

See also yii\elasticsearch\Command::$options.

public array $options = []
$postFilter public property (available since version 2.0.5)

The post_filter part of the search query for differentially filter search results and aggregations.

See also https://www.elastic.co/guide/en/elasticsearch/guide/current/_post_filter.html.

public string|array $postFilter null
$query public property

The query part of this search query. This is an array or json string that follows the format of the elasticsearch Query DSL.

public array|string $query null
$runtimeMappings public property

An array of runtime fields evaluated at query time Example: `php $query->$runtimeMappings = [

'value_times_two' => [
    'type' => 'double',
    'script' => "emit(doc['my_field_name'].value * 2)",
],
'value_times_factor' => [
    'type' => 'double',
    'script' => "emit(doc['my_field_name'].value * factor)",
    'params' => [
        'factor' => 2.0
    ],
],

] `

See also:

public array $runtimeMappings null
$scriptFields public property

The scripted fields being retrieved from the documents. Example: `php $query->scriptFields = [

'value_times_two' => [
    'script' => "doc['my_field_name'].value * 2",
],
'value_times_factor' => [
    'script' => "doc['my_field_name'].value * factor",
    'params' => [
        'factor' => 2.0
    ],
],

] `

Note: Field values are always returned as arrays even if they only have one value.

See also:

public array $scriptFields null
$source public property

This option controls how the _source field is returned from the documents. For example, ['id', 'name'] means that only the id and name field should be returned from _source. If not set, it means retrieving the full _source field unless fields() are specified. Setting this option to false will disable return of the _source field, this means that only the primaryKey of a record will be available in the result.

See also:

public array $source null
$stats public property

The 'stats' part of the query. An array of groups to maintain a statistics aggregation for.

See also https://www.elastic.co/guide/en/elasticsearch/reference/current/search.html#stats-groups.

public array $stats = []
$storedFields public property

The fields being retrieved from the documents. For example, ['id', 'name']. If not set, this option will not be applied to the query and no fields will be returned. In this case the _source field will be returned by default which can be configured using source(). Setting this to an empty array will result in no fields being retrieved, which means that only the primaryKey of a record will be available in the result. > Note: Field values are always returned as arrays even if they only > have one value.

See also:

public array $storedFields null
$suggest public property
public array $suggest = []
$timeout public property

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.

See also:

public integer $timeout null
$type public property

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 not set, all types are being queried.

See also from().

public string|array $type null

Method Details

Hide inherited methods

addAgg() public method
Deprecated since 2.0.5 use addAggregate() instead Adds an aggregation to this query. This is an alias for addAggregation().
public $this addAgg ( $name, $type, $options )
$name string

The name of the aggregation

$type string

The aggregation type. e.g. terms, range, histogram...

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

            
addAggregate() public method

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;
}

            
addAggregation() public method
Deprecated since 2.0.5 use addAggragate() instead Adds an aggregation to this query.
public $this addAggregation ( $name, $type, $options )
$name string

The name of the aggregation

$type string

The aggregation type. e.g. terms, range, histogram, ...

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

            
addCollapse() public method (available since version 2.1.0)
public $this addCollapse ( $collapse )
$collapse array

The configuration options for collapse.

return $this

The query object itself

                public function addCollapse($collapse)
{
    $this->collapse = $collapse;
    return $this;
}

            
addOptions() public method (available since version 2.0.4)

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\InvalidArgumentException

if $options is not an array

                public function addOptions($options)
{
    if (!is_array($options)) {
        throw new InvalidArgumentException('Array parameter expected, ' . gettype($options) . ' received.');
    }
    $this->options = array_merge($this->options, $options);
    return $this;
}

            
addSuggester() public method
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;
}

            
all() public method

Executes the query and returns all results as an array.

public array all ( $db null )
$db yii\elasticsearch\Connection

The database connection used to execute the query. If this parameter is not given, the elasticsearch application component 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)
{
    if ($this->emulateExecution) {
        return [];
    }
    $result = $this->createCommand($db)->search();
    if ($result === false) {
        throw new Exception('Elasticsearch search query failed.');
    }
    if (empty($result['hits']['hits'])) {
        return [];
    }
    $rows = $result['hits']['hits'];
    return $this->populate($rows);
}

            
andWhere() public method

public void andWhere ( $condition )
$condition

                public function andWhere($condition)
{
    if ($this->where === null) {
        $this->where = $condition;
    } else if (isset($this->where[0]) && $this->where[0] === 'and') {
        $this->where[] = $condition;
    } else {
        $this->where = ['and', $this->where, $condition];
    }
    return $this;
}

            
batch() public method (available since version 2.0.4)

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 elasticsearch application component will be used.

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

            
column() public method

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 elasticsearch application component will be used.

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 ($this->emulateExecution) {
        return [];
    }
    $command = $this->createCommand($db);
    $command->queryParts['_source'] = [$field];
    $result = $command->search();
    if ($result === false) {
        throw new Exception('Elasticsearch search query failed.');
    }
    if (empty($result['hits']['hits'])) {
        return [];
    }
    $column = [];
    foreach ($result['hits']['hits'] as $row) {
        if (isset($row['fields'][$field])) {
            $column[] = $row['fields'][$field];
        } elseif (isset($row['_source'][$field])) {
            $column[] = $row['_source'][$field];
        } else {
            $column[] = null;
        }
    }
    return $column;
}

            
count() public method

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 elasticsearch application component will be used.

return integer

Number of records

                public function count($q = '*', $db = null)
{
    if ($this->emulateExecution) {
        return 0;
    }
    $command = $this->createCommand($db);
    // performing a query with return size of 0, is equal to getting result stats such as count
    // https://www.elastic.co/guide/en/elasticsearch/reference/5.6/breaking_50_search_changes.html#_literal_search_type_literal
    $searchOptions = ['size' => 0];
    // Set track_total_hits to 'true' for ElasticSearch version 6 and up
    // https://www.elastic.co/guide/en/elasticsearch/reference/master/search-your-data.html#track-total-hits
    if ($command->db->dslVersion >= 6) {
        $searchOptions['track_total_hits'] = 'true';
    }
    $result = $command->search($searchOptions);
    // since ES7 totals are returned as array (with count and precision values)
    if (isset($result['hits']['total'])) {
        return is_array($result['hits']['total']) ? (int)$result['hits']['total']['value'] : (int)$result['hits']['total'];
    }
    return 0;
}

            
createCommand() public method

Creates a DB command that can be used to execute this query.

public yii\elasticsearch\Command createCommand ( $db null )
$db yii\elasticsearch\Connection

The database connection used to execute the query. If this parameter is not given, the elasticsearch application component will be used.

return yii\elasticsearch\Command

The created DB command instance.

                public function createCommand($db = null)
{
    if ($db === null) {
        $db = Yii::$app->get('elasticsearch');
    }
    $commandConfig = $db->getQueryBuilder()->build($this);
    return $db->createCommand($commandConfig);
}

            
delete() public method

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 elasticsearch application component will be used.

$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);
}

            
each() public method (available since version 2.0.4)

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 elasticsearch application component will be used.

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

            
exists() public method

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 elasticsearch application component will be used.

return boolean

Whether the query result contains any row of data.

                public function exists($db = null)
{
    return self::one($db) !== false;
}

            
explain() public method (available since version 2.0.5)

Explain for how the score of each document was computer

public $this explain ( $explain )
$explain

                public function explain($explain)
{
    $this->explain = $explain;
    return $this;
}

            
fields() public method

Sets the runtime fields to retrieve from the documents.

See also https://www.elastic.co/guide/en/elasticsearch/reference/current/runtime-retrieving-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;
}

            
from() public method
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 null it means that all indexes are being queried.

$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 null it means that all types are being queried.

return $this

The query object itself

                public function from($index, $type = null)
{
    $this->index = $index;
    $this->type = $type;
    return $this;
}

            
highlight() public method

Sets a highlight parameters to retrieve from the documents.

See also https://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;
}

            
init() public method

public void init ( )

                public function init()
{
    parent::init();
    // setting the default limit according to Elasticsearch defaults
    // https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-body.html#_parameters_5
    if ($this->limit === null) {
        $this->limit = 10;
    }
}

            
minScore() public method (available since version 2.0.4)
public $this minScore ( $minScore )
$minScore float

Exclude documents which have a _score less than the minimum specified minScore

return $this

The query object itself

                public function minScore($minScore)
{
    $this->minScore = $minScore;
    return $this;
}

            
one() public method

Executes the query and returns a single row of result.

public array|boolean one ( $db null )
$db yii\elasticsearch\Connection

The database connection used to execute the query. If this parameter is not given, the elasticsearch application component will be used.

return array|boolean

The first row (in terms of an array) of the query result. False is returned if the query results in nothing.

                public function one($db = null)
{
    if ($this->emulateExecution) {
        return false;
    }
    $result = $this->createCommand($db)->search(['size' => 1]);
    if ($result === false) {
        throw new Exception('Elasticsearch search query failed.');
    }
    if (empty($result['hits']['hits'])) {
        return false;
    }
    $record = reset($result['hits']['hits']);
    return $record;
}

            
options() public method (available since version 2.0.4)

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\InvalidArgumentException

if $options is not an array

                public function options($options)
{
    if (!is_array($options)) {
        throw new InvalidArgumentException('Array parameter expected, ' . gettype($options) . ' received.');
    }
    $this->options = $options;
    return $this;
}

            
orWhere() public method

public void orWhere ( $condition )
$condition

                public function orWhere($condition)
{
    if ($this->where === null) {
        $this->where = $condition;
    } else if (isset($this->where[0]) && $this->where[0] === 'or') {
        $this->where[] = $condition;
    } else {
        $this->where = ['or', $this->where, $condition];
    }
    return $this;
}

            
populate() public method (available since version 2.0.4)

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 ($this->indexBy === null) {
        return $rows;
    }
    $models = [];
    foreach ($rows as $key => $row) {
        if ($this->indexBy !== null) {
            if (is_string($this->indexBy)) {
                $key = isset($row['fields'][$this->indexBy]) ?
                    reset($row['fields'][$this->indexBy]) : $row['_source'][$this->indexBy];
            } else {
                $key = call_user_func($this->indexBy, $row);
            }
        }
        $models[$key] = $row;
    }
    return $models;
}

            
postFilter() public method (available since version 2.0.5)

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;
}

            
query() public method

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;
}

            
runtimeMappings() public method

Sets the runtime mappings for this query

See also https://www.elastic.co/guide/en/elasticsearch/reference/current/runtime.html.

public $this runtimeMappings ( $mappings )
$mappings
return $this

The query object itself

                public function runtimeMappings($mappings)
{
    if (is_array($mappings) || $mappings === null) {
        $this->runtimeMappings = $mappings;
    } else {
        $this->runtimeMappings = func_get_args();
    }
    return $this;
}

            
scalar() public method

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 elasticsearch application component will be used.

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;
}

            
scriptFields() public method

Sets the script fields to retrieve from the documents.

See also https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-script-fields.html.

public $this scriptFields ( $fields )
$fields array

The fields to be selected.

return $this

The query object itself

                public function scriptFields($fields)
{
    if (is_array($fields) || $fields === null) {
        $this->scriptFields = $fields;
    } else {
        $this->scriptFields = func_get_args();
    }
    return $this;
}

            
search() public method

Executes the query and returns the complete search result including e.g.

hits, aggregations, suggesters, 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 elasticsearch application component will be used.

$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);
    if ($result === false) {
        throw new Exception('Elasticsearch search query failed.');
    }
    if (!empty($result['hits']['hits']) && $this->indexBy !== null) {
        $rows = [];
        foreach ($result['hits']['hits'] as $key => $row) {
            if (is_string($this->indexBy)) {
                $key = isset($row['fields'][$this->indexBy]) ?
                    $row['fields'][$this->indexBy] : $row['_source'][$this->indexBy];
            } else {
                $key = call_user_func($this->indexBy, $row);
            }
            $rows[$key] = $row;
        }
        $result['hits']['hits'] = $rows;
    }
    return $result;
}

            
source() public method

Sets the source filtering, specifying how the _source field of the document should be returned.

See also https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-source-filtering.html.

public $this source ( $source )
$source array|string|null|false

The source patterns to be selected.

return $this

The query object itself

                public function source($source)
{
    if (is_array($source) || $source === null  || $source === false) {
        $this->source = $source;
    } else {
        $this->source = func_get_args();
    }
    return $this;
}

            
stats() public method
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;
}

            
storedFields() public method

Sets the fields to retrieve from the documents.

Quote from the Elasticsearch doc: > The stored_fields parameter is about fields that are explicitly marked > as stored in the mapping, which is off by default and generally not > recommended. Use source filtering instead to select subsets of the > original source document to be returned.

See also https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-stored-fields.html.

public $this storedFields ( $fields )
$fields array

The fields to be selected.

return $this

The query object itself

                public function storedFields($fields)
{
    if (is_array($fields) || $fields === null) {
        $this->storedFields = $fields;
    } else {
        $this->storedFields = func_get_args();
    }
    return $this;
}

            
timeout() public method
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;
}