Class Query
Constants
Property Summary
-
$_cache protected
Cake\Datasource\QueryCacher|null
A query cacher instance if this query has caching enabled.
-
$_dirty protected
bool
Internal state to track whether or not the query has been modified.
-
$_elasticQuery protected
Elastica\Query
The Elastica Query object that is to be executed after being built.
-
$_formatters protected
arrayClosure>
List of formatter classes or callbacks that will post-process the results when fetched
-
$_mapReduce protected
array
List of map-reduce routines that should be applied over the query result
-
$_options protected
array
Holds any custom options passed using applyOptions that could not be processed by any method in this class.
-
$_queryParts protected
array
The various query builder parts that will be transferred to the elastica query.
-
$_repository protected
Cake\ElasticSearch\Index
Instance of a repository object this query is bound to.
-
$_results protected
iterable|null
A ResultSet.
-
$_searchOptions protected
array
Additional options for Elastica\Index::search()
Method Summary
-
__construct() public
Query constructor
-
_buildBoolQuery() protected
Auxiliary function used to parse conditions into bool query and store them in a _queryParts variable.
-
_execute() protected
Executes the query.
-
aggregate() public
Add an aggregation to the elastic query object
-
aliasField() public
Returns a key => value array representing a single aliased field that can be passed directly to the select() method. The key will contain the alias and the value the actual field name.
-
aliasFields() public
Runs
aliasField()
for each field in the provided list and returns the result under a single array. -
all() public
Fetch the results for this query.
-
andWhere() public
Connects any previously defined set of conditions to the provided list using the AND operator. This function accepts the conditions list in the same format as the method
where
does, hence you can use arrays, expression objects callback functions or strings. -
applyOptions() public
Populates or adds parts to current query clauses using an array. This is handy for passing all query clauses at once. The option array accepts:
-
cache() public
Enable result caching for this query.
-
clause() public
Returns any data that was stored in the specified clause. This is useful for modifying any internal part of the query and it is used during compiling to transform the query accordingly before it is executed. The valid clauses that can be retrieved are: fields, filter, postFilter, query, order, limit and offset.
-
collapse() public
Add collapse to the elastic query object
-
compileQuery() public
Compile the Elasticsearch query.
-
count() public
Returns the total amount of hits for the query
-
decorateResults() protected
Decorates the results iterator with MapReduce routines and formatters
-
decoratorClass() protected
Returns the name of the class to be used for decorating results
-
find() public
Apply custom finds to against an existing query object.
-
first() public
Returns the first result out of executing this query, if the query has not been executed before, it will set the limit clause to 1 for performance reasons.
-
firstOrFail() public
Get the first result from the executing query or raise an exception.
-
formatResults() public
Registers a new formatter callback function that is to be executed when trying to fetch the results from the database.
-
getIterator() public
Executes this query and returns a results iterator. This function is required for implementing the IteratorAggregate interface and allows the query to be iterated without having to call execute() manually, thus making it look like a result set instead of the query itself.
-
getMapReducers() public
Returns the list of previously registered map reduce routines.
-
getOptions() public
Returns an array with the custom options that were applied to this query and that were not already processed by another method in this class.
-
getRepository() public
Returns the default repository object that will be used by this query, that is, the table that will appear in the from clause.
-
getResultFormatters() public
Returns the list of previously registered format routines.
-
highlight() public
Set the highlight options for the query.
-
limit() public
Sets the maximum number of results to return for this query. This sets the
size
option for the Elasticsearch query. -
mapReduce() public
Register a new MapReduce routine to be executed on top of the database results
-
offset() public
Sets the number of records that should be skipped from the original result set This is commonly used for paginating large results. Accepts an integer.
-
order() public deprecated
Sets the sorting options for the result set.
-
orderBy() public
Sets the sorting options for the result set.
-
page() public
Set the page of results you want.
-
postFilter() public
Sets the query to use in the post_filter object. Filters added using this method will be stacked on a BoolQuery.
-
queryMust() public
Modifies the query part, taking scores in account. Queries added using this method will be stacked on a bool query and applied to the
must
part of the final BoolQuery. -
queryShould() public
Modifies the query part, taking scores in account. Queries added using this method will be stacked on a bool query and applied to the
should
part of the final BoolQuery. -
repository() public deprecated
Set the default repository object that will be used by this query.
-
searchOptions() public
Set or get the search options
-
select() public
Adds fields to be selected from _source.
-
setFullQuery() public
Method to set or overwrite the query
-
setRepository() public
Set the default repository object that will be used by this query.
-
toArray() public
Returns an array representation of the results after executing the query.
-
where() public
Sets the filter to use in the query object. Queries added using this method will be stacked on a bool query and applied to the filter part of the final BoolQuery.
-
withMinScore() public
Sets the minim score the results should have in order to be returned in the resultset
Method Detail
__construct() ¶ public
__construct(Cake\ElasticSearch\Index $repository)
Query constructor
Parameters
-
Cake\ElasticSearch\Index
$repository The type of document.
_buildBoolQuery() ¶ protected
_buildBoolQuery(string $partType, Elastica\Query\AbstractQuery|callable|array $conditions, bool $overwrite, string $type = 'addMust'): $this
Auxiliary function used to parse conditions into bool query and store them in a _queryParts variable.
Parameters
-
string
$partType The name of the part in which the bool query will be stored
-
Elastica\Query\AbstractQuery|callable|array
$conditions The list of conditions.
-
bool
$overwrite Whether or not to replace previous query.
-
string
$type optional The method to use for appending the conditions to the Query
Returns
$this
_execute() ¶ protected
_execute(): Cake\ElasticSearch\ResultSet
Executes the query.
Returns
Cake\ElasticSearch\ResultSet
aggregate() ¶ public
aggregate(Elastica\Aggregation\AbstractAggregation|array $aggregation): $this
Add an aggregation to the elastic query object
Parameters
-
Elastica\Aggregation\AbstractAggregation|array
$aggregation One or multiple facets
Returns
$this
aliasField() ¶ public
aliasField(string $field, string|null $alias = null): array<string, string>
Returns a key => value array representing a single aliased field that can be passed directly to the select() method. The key will contain the alias and the value the actual field name.
If the field is already aliased, then it will not be changed. If no $alias is passed, the default table for this query will be used.
Parameters
-
string
$field -
string|null
$alias optional
Returns
array<string, string>
aliasFields() ¶ public
aliasFields(array $fields, string|null $defaultAlias = null): array<string, string>
Runs aliasField()
for each field in the provided list and returns
the result under a single array.
Parameters
-
array
$fields -
string|null
$defaultAlias optional
Returns
array<string, string>
all() ¶ public
all(): Cake\Datasource\ResultSetInterface
Fetch the results for this query.
Will return either the results set through setResult(), or execute this query and return the ResultSetDecorator object ready for streaming of results.
ResultSetDecorator is a traversable object that implements the methods found on Cake\Collection\Collection.
Returns
Cake\Datasource\ResultSetInterface
andWhere() ¶ public
andWhere(Elastica\Query\AbstractQuery|callable|array|null $conditions, array $types = []): $this
Connects any previously defined set of conditions to the provided list
using the AND operator. This function accepts the conditions list in the same
format as the method where
does, hence you can use arrays, expression objects
callback functions or strings.
It is important to notice that when calling this function, any previous set of conditions defined for this query will be treated as a single argument for the AND operator. This function will not only operate the most recently defined condition, but all the conditions as a whole.
When using an array for defining conditions, creating constraints form each
array entry will use the same logic as with the where()
function. This means
that each array entry will be joined to the other using the AND operator, unless
you nest the conditions in the array using other operator.
Examples:
$query->where(['title' => 'Hello World')->andWhere(['author_id' => 1]);
Will produce:
WHERE title = 'Hello World' AND author_id = 1
$query
->where(['OR' => ['published' => false, 'published is NULL']])
->andWhere(['author_id' => 1, 'comments_count >' => 10])
Produces:
WHERE (published = 0 OR published IS NULL) AND author_id = 1 AND comments_count > 10
$query
->where(['title' => 'Foo'])
->andWhere(function ($exp, $query) {
return $exp
->or(['author_id' => 1])
->add(['author_id' => 2]);
});
Generates the following conditions:
WHERE (title = 'Foo') AND (author_id = 1 OR author_id = 2)
Parameters
-
Elastica\Query\AbstractQuery|callable|array|null
$conditions The list of conditions.
-
array
$types optional Not used, required to comply with QueryInterface.
Returns
$this
See Also
\Cake\ElasticSearch\QueryBuilder
applyOptions() ¶ public
applyOptions(array<string, mixed> $options): $this
Populates or adds parts to current query clauses using an array. This is handy for passing all query clauses at once. The option array accepts:
- fields: Maps to the select method
- conditions: Maps to the where method
- order: Maps to the order method
- limit: Maps to the limit method
- offset: Maps to the offset method
- page: Maps to the page method
Example:
$query->applyOptions([
'fields' => ['id', 'name'],
'conditions' => [
'created >=' => '2013-01-01'
],
'limit' => 10
]);
Is equivalent to:
$query
->select(['id', 'name'])
->where(['created >=' => '2013-01-01'])
->limit(10)
Parameters
-
array<string, mixed>
$options list of query clauses to apply new parts to.
Returns
$this
cache() ¶ public
cache(Closure|string|false $key, Psr\SimpleCache\CacheInterface|string $config = 'default'): $this
Enable result caching for this query.
If a query has caching enabled, it will do the following when executed:
- Check the cache for $key. If there are results no SQL will be executed. Instead the cached results will be returned.
- When the cached data is stale/missing the result set will be cached as the query is executed.
Usage
// Simple string key + config
$query->cache('my_key', 'db_results');
// Function to generate key.
$query->cache(function ($q) {
$key = serialize($q->clause('select'));
$key .= serialize($q->clause('where'));
return md5($key);
});
// Using a pre-built cache engine.
$query->cache('my_key', $engine);
// Disable caching
$query->cache(false);
Parameters
-
Closure|string|false
$key Either the cache key or a function to generate the cache key. When using a function, this query instance will be supplied as an argument.
-
Psr\SimpleCache\CacheInterface|string
$config optional Either the name of the cache config to use, or a cache engine instance.
Returns
$this
clause() ¶ public
clause(string $name): mixed
Returns any data that was stored in the specified clause. This is useful for modifying any internal part of the query and it is used during compiling to transform the query accordingly before it is executed. The valid clauses that can be retrieved are: fields, filter, postFilter, query, order, limit and offset.
The return value for each of those parts may vary. Some clauses use QueryExpression to internally store their state, some use arrays and others may use booleans or integers. This is summary of the return types for each clause.
- fields: array, will return empty array when no fields are set
- query: The final BoolQuery to be used in the query (with scoring) part.
- filter: The query to use in the final BoolQuery filter object, returns null when not set
- postFilter: The query to use in the post_filter object, returns null when not set
- order: OrderByExpression, returns null when not set
- limit: integer, null when not set
- offset: integer, null when not set
Parameters
-
string
$name name of the clause to be returned
Returns
mixed
collapse() ¶ public
collapse(Elastica\Collapse|string $collapse): $this
Add collapse to the elastic query object
Parameters
-
Elastica\Collapse|string
$collapse Collapse field or elastic collapse object
Returns
$this
compileQuery() ¶ public
compileQuery(): Elastica\Query
Compile the Elasticsearch query.
Returns
Elastica\Query
decorateResults() ¶ protected
decorateResults(iterable $result): Cake\Datasource\ResultSetInterface
Decorates the results iterator with MapReduce routines and formatters
Parameters
-
iterable
$result Original results
Returns
Cake\Datasource\ResultSetInterface
decoratorClass() ¶ protected
decoratorClass(): class-stringCake\Datasource\ResultSetInterface>
Returns the name of the class to be used for decorating results
Returns
class-stringCake\Datasource\ResultSetInterface>
find() ¶ public
find(string $finder, mixed ...$args): static<TSubject>
Apply custom finds to against an existing query object.
Allows custom find methods to be combined and applied to each other.
$repository->find('all')->find('recent');
The above is an example of stacking multiple finder methods onto a single query.
Parameters
-
string
$finder The finder method to use.
-
mixed
...$args The options for the finder.
Returns
static<TSubject>
first() ¶ public
first(): mixed
Returns the first result out of executing this query, if the query has not been executed before, it will set the limit clause to 1 for performance reasons.
Example:
$singleUser = $query->select(['id', 'username'])->first();
Returns
mixed
firstOrFail() ¶ public
firstOrFail(): mixed
Get the first result from the executing query or raise an exception.
Returns
mixed
Throws
Cake\Datasource\Exception\RecordNotFoundException
When there is no first record.
formatResults() ¶ public
formatResults(Closure|null $formatter = null, int|bool $mode = self::APPEND): $this
Registers a new formatter callback function that is to be executed when trying to fetch the results from the database.
If the second argument is set to true, it will erase previous formatters and replace them with the passed first argument.
Callbacks are required to return an iterator object, which will be used as
the return value for this query's result. Formatter functions are applied
after all the MapReduce
routines for this query have been executed.
Formatting callbacks will receive two arguments, the first one being an object
implementing \Cake\Collection\CollectionInterface
, that can be traversed and
modified at will. The second one being the query instance on which the formatter
callback is being applied.
Examples:
Return all results from the table indexed by id:
$query->select(['id', 'name'])->formatResults(function ($results) {
return $results->indexBy('id');
});
Add a new column to the ResultSet:
$query->select(['name', 'birth_date'])->formatResults(function ($results) {
return $results->map(function ($row) {
$row['age'] = $row['birth_date']->diff(new DateTime)->y;
return $row;
});
});
Parameters
-
Closure|null
$formatter optional The formatting function
-
int|bool
$mode optional Whether to overwrite, append or prepend the formatter.
Returns
$this
Throws
InvalidArgumentException
getIterator() ¶ public
getIterator(): Traversable
Executes this query and returns a results iterator. This function is required for implementing the IteratorAggregate interface and allows the query to be iterated without having to call execute() manually, thus making it look like a result set instead of the query itself.
Returns
Traversable
getMapReducers() ¶ public
getMapReducers(): array
Returns the list of previously registered map reduce routines.
Returns
array
getOptions() ¶ public
getOptions(): array
Returns an array with the custom options that were applied to this query and that were not already processed by another method in this class.
Example:
$query->applyOptions(['doABarrelRoll' => true, 'fields' => ['id', 'name']);
$query->getOptions(); // Returns ['doABarrelRoll' => true]
Returns
array
See Also
applyOptions()
getRepository() ¶ public
getRepository(): Cake\ElasticSearch\Index
Returns the default repository object that will be used by this query, that is, the table that will appear in the from clause.
Returns
Cake\ElasticSearch\Index
getResultFormatters() ¶ public
getResultFormatters(): arrayClosure>
Returns the list of previously registered format routines.
Returns
arrayClosure>
highlight() ¶ public
highlight(array $highlight): $this
Set the highlight options for the query.
Parameters
-
array
$highlight The highlight options to use.
Returns
$this
limit() ¶ public
limit(int|null $limit): $this
Sets the maximum number of results to return for this query.
This sets the size
option for the Elasticsearch query.
Examples
$query->limit(10) // generates LIMIT 10
$query->limit($query->newExpr()->add(['1 + 1'])); // LIMIT (1 + 1)
Parameters
-
int|null
$limit The number of documents to return.
Returns
$this
mapReduce() ¶ public
mapReduce(Closure|null $mapper = null, Closure|null $reducer = null, bool $overwrite = false): $this
Register a new MapReduce routine to be executed on top of the database results
The MapReduce routing will only be run when the query is executed and the first result is attempted to be fetched.
If the third argument is set to true, it will erase previous map reducers and replace it with the arguments passed.
Parameters
-
Closure|null
$mapper optional The mapper function
-
Closure|null
$reducer optional The reducing function
-
bool
$overwrite optional Set to true to overwrite existing map + reduce functions.
Returns
$this
See Also
offset() ¶ public
offset(int|null $offset): $this
Sets the number of records that should be skipped from the original result set This is commonly used for paginating large results. Accepts an integer.
In some databases, this operation might not be supported or will require the query to be transformed in order to limit the result set size.
Examples
$query->offset(10) // generates OFFSET 10
$query->offset($query->newExpr()->add(['1 + 1'])); // OFFSET (1 + 1)
Parameters
-
int|null
$offset The number of records to be skipped
Returns
$this
order() ¶ public
order(Closure|array|string $fields, bool $overwrite = false): $this
Sets the sorting options for the result set.
The accepted format for the $order parameter is:
- [['name' => ['order'=> 'asc', ...]], ['price' => ['order'=> 'asc', ...]]]
- ['name' => 'asc', 'price' => 'desc']
- 'field1' (defaults to order => 'desc')
Parameters
-
Closure|array|string
$fields The sorting order to use.
-
bool
$overwrite optional Whether or not to replace previous sorting.
Returns
$this
orderBy() ¶ public
orderBy(Closure|array|string $fields, bool $overwrite = false): $this
Sets the sorting options for the result set.
The accepted format for the $order parameter is:
- [['name' => ['order'=> 'asc', ...]], ['price' => ['order'=> 'asc', ...]]]
- ['name' => 'asc', 'price' => 'desc']
- 'field1' (defaults to order => 'desc')
Parameters
-
Closure|array|string
$fields The sorting order to use.
-
bool
$overwrite optional Whether or not to replace previous sorting.
Returns
$this
page() ¶ public
page(int $num, int|null $limit = null): $this
Set the page of results you want.
This method provides an easier to use interface to set the limit + offset
in the record set you want as results. If empty the limit will default to
the existing limit clause, and if that too is empty, then 25
will be used.
Pages should start at 1.
Parameters
-
int
$num The page number you want.
-
int|null
$limit optional The number of rows you want in the page. If null the current limit clause will be used.
Returns
$this
postFilter() ¶ public
postFilter(Elastica\Query\AbstractQuery|callable|array $conditions, bool $overwrite = false): $this
Sets the query to use in the post_filter object. Filters added using this method will be stacked on a BoolQuery.
This method can be used in the same way the where()
method is used. Please refer to
its documentation for more details.
Parameters
-
Elastica\Query\AbstractQuery|callable|array
$conditions The list of conditions.
-
bool
$overwrite optional Whether or not to replace previous filters.
Returns
$this
See Also
queryMust() ¶ public
queryMust(Elastica\Query\AbstractQuery|callable|array $conditions, bool $overwrite = false): $this
Modifies the query part, taking scores in account. Queries added using this method
will be stacked on a bool query and applied to the must
part of the final BoolQuery.
This method can be used in the same way the where()
method is used. Please refer to
its documentation for more details.
Parameters
-
Elastica\Query\AbstractQuery|callable|array
$conditions The list of conditions
-
bool
$overwrite optional Whether or not to replace previous queries.
Returns
$this
queryShould() ¶ public
queryShould(Elastica\Query\AbstractQuery|callable|array $conditions, bool $overwrite = false): $this
Modifies the query part, taking scores in account. Queries added using this method
will be stacked on a bool query and applied to the should
part of the final BoolQuery.
This method can be used in the same way the where()
method is used. Please refer to
its documentation for more details.
Parameters
-
Elastica\Query\AbstractQuery|callable|array
$conditions The list of conditions
-
bool
$overwrite optional Whether or not to replace previous queries.
Returns
$this
repository() ¶ public
repository(Cake\Datasource\RepositoryInterface $repository): $this
Set the default repository object that will be used by this query.
Parameters
-
Cake\Datasource\RepositoryInterface
$repository The default repository object to use.
Returns
$this
searchOptions() ¶ public
searchOptions(array|null $options = null): $this|array
Set or get the search options
Parameters
-
array|null
$options optional An array of additional search options
Returns
$this|array
select() ¶ public
select(Closure|array|string|float|int $fields, bool $overwrite = false): $this
Adds fields to be selected from _source.
Calling this function multiple times will append more fields to the list of fields to be selected from _source.
If true
is passed in the second argument, any previous selections
will be overwritten with the list passed in the first argument.
Parameters
-
Closure|array|string|float|int
$fields The list of fields to select from _source.
-
bool
$overwrite optional Whether or not to replace previous selections.
Returns
$this
setFullQuery() ¶ public
setFullQuery(Elastica\Query\AbstractQuery $query): $this
Method to set or overwrite the query
Parameters
-
Elastica\Query\AbstractQuery
$query Set the query
Returns
$this
setRepository() ¶ public
setRepository(Cake\Datasource\RepositoryInterface $repository): $this
Set the default repository object that will be used by this query.
Parameters
-
Cake\Datasource\RepositoryInterface
$repository The default repository object to use.
Returns
$this
toArray() ¶ public
toArray(): array
Returns an array representation of the results after executing the query.
Returns
array
where() ¶ public
where(Closure|array|string|null $conditions = null, array<string, string> $types = [], bool $overwrite = false): $this
Sets the filter to use in the query object. Queries added using this method will be stacked on a bool query and applied to the filter part of the final BoolQuery.
Filters added with this method will have no effect in the final score of the documents, and the documents that do not match the specified filters will be left out.
There are several way in which you can use this method. The easiest one is by passing a simple array of conditions:
{{{ // Generates a {"term": {"name": "jose"}} json query $query->where(['name' => 'jose']); }}}
You can have as many conditions in the array as you'd like, Operators are also allowed in the field side of the array:
{{{ $query->where(['name' => 'jose', 'age >' => 30, 'interests in' => ['php', 'cake']); }}}
You can read about the available operators and how they translate to Elasticsearch
queries in the Cake\ElasticSearch\QueryBuilder::parse()
method documentation.
Additionally, it is possible to use a closure as first argument. The closure will receive a QueryBuilder instance, that you can use for creating arbitrary queries combinations:
{{{ $query->where(function ($builder) { return $builder->and($builder->between('age', 10, 20), $builder->missing('name')); }); }}}
Finally, you can pass any already built queries as first argument:
{{{ $query->where(new \Elastica\Filter\Term('name.first', 'jose')); }}{
Parameters
-
Closure|array|string|null
$conditions optional The list of conditions.
-
array<string, string>
$types optional Not used, required to comply with QueryInterface.
-
bool
$overwrite optional Whether or not to replace previous queries.
Returns
$this
See Also
withMinScore() ¶ public
withMinScore(float $score): $this
Sets the minim score the results should have in order to be returned in the resultset
Parameters
-
float
$score The minimum score to observe
Returns
$this
Property Detail
$_cache ¶ protected
A query cacher instance if this query has caching enabled.
Type
Cake\Datasource\QueryCacher|null
$_elasticQuery ¶ protected
The Elastica Query object that is to be executed after being built.
Type
Elastica\Query
$_formatters ¶ protected
List of formatter classes or callbacks that will post-process the results when fetched
Type
arrayClosure>
$_mapReduce ¶ protected
List of map-reduce routines that should be applied over the query result
Type
array
$_options ¶ protected
Holds any custom options passed using applyOptions that could not be processed by any method in this class.
Type
array
$_queryParts ¶ protected
The various query builder parts that will be transferred to the elastica query.
Type
array
$_repository ¶ protected
Instance of a repository object this query is bound to.
Type
Cake\ElasticSearch\Index