Class Query
Constants
-
integer
APPEND ¶0
Indicates that the operation should append to the list
-
string
JOIN_TYPE_INNER ¶'INNER'
-
string
JOIN_TYPE_LEFT ¶'LEFT'
-
string
JOIN_TYPE_RIGHT ¶'RIGHT'
-
boolean
OVERWRITE ¶true
Indicates that the operation should overwrite the list
-
integer
PREPEND ¶1
Indicates that the operation should prepend to the list
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.
-
$_eagerLoaded protected
bool
Whether the query is standalone or the product of an eager load operation.
-
$_elasticQuery protected
Elastica\Query
The Elastica Query object that is to be executed after being built.
-
$_formatters protected
callable[]
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\Datasource\RepositoryInterface
Instance of a table object this query is bound to
-
$_results protected
Cake\Datasource\ResultSetInterface|null
A ResultSet.
-
$_searchOptions protected
array
Additional options for Elastica\Type::search()
Method Summary
-
__call() public
Enables calling methods from the result set as if they were from this class
-
__construct() public
Query constructor
-
_buildBoolQuery() protected
Auxiliary function used to parse conditions into bool query and store them in a _queryParts variable.
-
_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
-
_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 @method
-
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.
-
compileQuery() public
Compile the Elasticsearch query.
-
count() public
Returns the total amount of hits for the query
-
eagerLoaded() public deprecated
Sets the query instance to be an eager loaded query. If no argument is passed, the current configured query
_eagerLoaded
value is returned. -
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 table 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.
-
isEagerLoaded() public
Returns the current configured query
_eagerLoaded
value -
limit() public
Sets the maximum number of results to return for this query. This sets the
size
option for the Elastic Search query. -
mapReduce() public
Register a new MapReduce routine to be executed on top of the database results Both the mapper and caller callable should be invokable objects.
-
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
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
Returns the default table object that will be used by this query, that is, the table that will appear in the from clause.
-
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
-
setResult() public
Set the result set for a 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
__call() ¶ public
__call(string $method, array $arguments): mixed
Enables calling methods from the result set as if they were from this class
Parameters
-
string
$method the method to call
-
array
$arguments list of arguments for the method to call
Returns
mixed
Throws
BadMethodCallException
if no such method exists in result set
__construct() ¶ public
__construct(Cake\ElasticSearch\Index $repository)
Query constructor
Parameters
-
Cake\ElasticSearch\Index
$repository The type of document.
_buildBoolQuery() ¶ protected
_buildBoolQuery(string $partType, array|callable|Elastica\Query\AbstractQuery $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
-
array|callable|Elastica\Query\AbstractQuery
$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
_decorateResults() ¶ protected
_decorateResults(Traversable $result): Cake\Datasource\ResultSetInterface
Decorates the results iterator with MapReduce routines and formatters
Parameters
-
Traversable
$result Original results
Returns
Cake\Datasource\ResultSetInterface
_decoratorClass() ¶ protected
_decoratorClass(): string
Returns the name of the class to be used for decorating results
Returns
string
_execute() ¶ protected
_execute(): Cake\ElasticSearch\ResultSet
Executes the query.
Returns
Cake\ElasticSearch\ResultSet
aggregate() ¶ public
aggregate(array|Elastica\Aggregation\AbstractAggregation $aggregation): $this
Add an aggregation to the elastic query object
Parameters
-
array|Elastica\Aggregation\AbstractAggregation
$aggregation One or multiple facets
Returns
$this
aliasField() ¶ public
aliasField(string $field, string|null $alias = null): array
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
aliasFields() ¶ public
aliasFields(array $fields, string|null $defaultAlias = null): array
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
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 @method
andWhere(mixed $conditions, mixed $types = []): $this
Parameters
-
$conditions
-
$types optional
Returns
$this
applyOptions() ¶ public
applyOptions(array $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
$options list of query clauses to apply new parts to.
Returns
$this
cache() ¶ public
cache(Closure|string|false $key, string|Cake\Cache\CacheEngine $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.
-
string|Cake\Cache\CacheEngine
$config optional Either the name of the cache config to use, or a cache config 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
eagerLoaded() ¶ public
eagerLoaded(bool|null $value = null): $this|bool
Sets the query instance to be an eager loaded query. If no argument is
passed, the current configured query _eagerLoaded
value is returned.
Parameters
-
bool|null
$value optional Whether or not to eager load.
Returns
$this|bool
find() ¶ public
find(string $finder = 'all', array $options = []): Cake\ElasticSearch\Query
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 optional The finder method to use.
-
array
$options optional The options for the finder.
Returns
Cake\ElasticSearch\Query
first() ¶ public
first(): Cake\Datasource\EntityInterface|array|null
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
Cake\Datasource\EntityInterface|array|null
firstOrFail() ¶ public
firstOrFail(): Cake\Datasource\EntityInterface|array
Get the first result from the executing query or raise an exception.
Returns
Cake\Datasource\EntityInterface|array
Throws
Cake\Datasource\Exception\RecordNotFoundException
When there is no first record.
formatResults() ¶ public
formatResults(callable|null $formatter = null, bool|int $mode = 0): $this|array
Registers a new formatter callback function that is to be executed when trying to fetch the results from the database.
Formatting callbacks will get a first parameter, an object implementing
\Cake\Collection\CollectionInterface
, that can be traversed and modified at will.
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.
If the first argument is set to null, it will return the list of previously registered format routines. This is deprecated as of 3.6.0 - use getResultFormatters() instead.
If the second argument is set to true, it will erase previous formatters and replace them with the passed first argument.
Example:
// 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
-
callable|null
$formatter optional The formatting callable.
-
bool|int
$mode optional Whether or not to overwrite, append or prepend the formatter.
Returns
$this|array
getIterator() ¶ public
getIterator(): Iterator
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
Iterator
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
getRepository() ¶ public
getRepository(): Cake\Datasource\RepositoryInterface
Returns the default table object that will be used by this query, that is, the table that will appear in the from clause.
Returns
Cake\Datasource\RepositoryInterface
getResultFormatters() ¶ public
getResultFormatters(): array
Returns the list of previously registered format routines.
Returns
array
highlight() ¶ public
highlight(array $highlight): $this
Set the highlight options for the query.
Parameters
-
array
$highlight The highlight options to use.
Returns
$this
isEagerLoaded() ¶ public
isEagerLoaded(): bool
Returns the current configured query _eagerLoaded
value
Returns
bool
limit() ¶ public
limit(int $limit): $this
Sets the maximum number of results to return for this query.
This sets the size
option for the Elastic Search query.
Examples
$query->limit(10) // generates LIMIT 10
$query->limit($query->newExpr()->add(['1 + 1'])); // LIMIT (1 + 1)
Parameters
-
int
$limit The number of documents to return.
Returns
$this
mapReduce() ¶ public
mapReduce(callable|null $mapper = null, callable|null $reducer = null, bool $overwrite = false): $this|array
Register a new MapReduce routine to be executed on top of the database results Both the mapper and caller callable should be invokable objects.
The MapReduce routing will only be run when the query is executed and the first result is attempted to be fetched.
If the first argument is set to null, it will return the list of previously registered map reduce routines. This is deprecated as of 3.6.0 - use getMapReducers() instead.
If the third argument is set to true, it will erase previous map reducers and replace it with the arguments passed.
Parameters
-
callable|null
$mapper optional The mapper callable.
-
callable|null
$reducer optional The reducing function.
-
bool
$overwrite optional Set to true to overwrite existing map + reduce functions.
Returns
$this|array
See Also
offset() ¶ public
offset(int $num): $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
$num The number of records to be skipped
Returns
$this
order() ¶ public
order(string|array $order, 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
-
string|array
$order 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(array|callable|Elastica\Query\AbstractQuery $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
-
array|callable|Elastica\Query\AbstractQuery
$conditions The list of conditions.
-
bool
$overwrite optional Whether or not to replace previous filters.
Returns
$this
See Also
queryMust() ¶ public
queryMust(array|callable|Elastica\Query\AbstractQuery $conditions, bool $overwrite = false): Query
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
-
array|callable|Elastica\Query\AbstractQuery
$conditions The list of conditions
-
bool
$overwrite optional Whether or not to replace previous queries.
Returns
Query
queryShould() ¶ public
queryShould(array|callable|Elastica\Query\AbstractQuery $conditions, bool $overwrite = false): Query
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
-
array|callable|Elastica\Query\AbstractQuery
$conditions The list of conditions
-
bool
$overwrite optional Whether or not to replace previous queries.
Returns
Query
repository() ¶ public
repository(Cake\Datasource\RepositoryInterface|null $table = null): Cake\Datasource\RepositoryInterface|$this
Returns the default table object that will be used by this query, that is, the table that will appear in the from clause.
When called with a Table argument, the default table object will be set and this query object will be returned for chaining.
Deprecated: 3.6.0 Using Query::repository() as getter is deprecated. Use getRepository() instead.
Parameters
-
Cake\Datasource\RepositoryInterface|null
$table optional The default table object to use
Returns
Cake\Datasource\RepositoryInterface|$this
searchOptions() ¶ public
searchOptions(null|array $options = null): $this|array
Set or get the search options
Parameters
-
null|array
$options optional An array of additional search options
Returns
$this|array
select() ¶ public
select(array $fields, mixed $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
-
array
$fields The list of fields to select from _source.
-
$overwrite optional
Whether or not to replace previous selections.
Returns
$this
setFullQuery() ¶ public
setFullQuery(AbstractQuery $query): $this
Method to set or overwrite the query
Parameters
-
AbstractQuery
$query Set the query
Returns
$this
setResult() ¶ public
setResult(Cake\Datasource\ResultSetInterface $results): $this
Set the result set for a query.
Setting the resultset of a query will make execute() a no-op. Instead of executing the SQL query and fetching results, the ResultSet provided to this method will be returned.
This method is most useful when combined with results stored in a persistent cache.
Parameters
-
Cake\Datasource\ResultSetInterface
$results The results this query should return.
Returns
$this
toArray() ¶ public
toArray(): array
Returns an array representation of the results after executing the query.
Returns
array
where() ¶ public
where(string|array|callable|null $conditions = null, array $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 allowe 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 Elastic Search
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
-
string|array|callable|null
$conditions optional The list of conditions.
-
array
$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
$_eagerLoaded ¶ protected
Whether the query is standalone or the product of an eager load operation.
Type
bool
$_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
callable[]
$_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 table object this query is bound to
Type
Cake\Datasource\RepositoryInterface
$_results ¶ protected
A ResultSet.
When set, query execution will be bypassed.
Type
Cake\Datasource\ResultSetInterface|null