CakePHP
  • Documentation
    • Book
    • API
    • Videos
    • Reporting Security Issues
    • Privacy Policy
    • Logos & Trademarks
  • Business Solutions
  • Swag
  • Road Trip
  • Team
  • Community
    • Community
    • Get Involved
    • Issues (Github)
    • Bakery
    • Featured Resources
    • Training
    • Meetups
    • My CakePHP
    • CakeFest
    • Newsletter
    • Linkedin
    • YouTube
    • Facebook
    • Twitter
    • Mastodon
    • Help & Support
    • Forum
    • Stack Overflow
    • IRC
    • Slack
    • Paid Support
CakePHP

C Elastic Search 3.x API

  • Project:
    • Elastic Search
      • CakePHP
      • Authentication
      • Authorization
      • Chronos
      • Elastic Search
      • Queue
  • Version:
    • 3.x
      • 4.x
      • 3.x
      • 2.x

Namespaces

  • Cake\ElasticSearch
    • Association
    • Datasource
    • Exception
    • Rule
    • TestSuite
    • View

Class Query

Namespace: Cake\ElasticSearch

Constants

  • int
    APPEND ¶
    0

    Indicates that the operation should append to the list

  • bool
    OVERWRITE ¶
    true

    Indicates that the operation should overwrite the list

  • int
    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
    array<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
    iterable|null

    A ResultSet.

  • $_searchOptions protected
    array

    Additional options for Elastica\Index::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

    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.

  • append() public deprecated
  • appendItem() public deprecated
  • 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:

  • avg() public deprecated
  • buffered() public deprecated
  • cache() public

    Enable result caching for this query.

  • cartesianProduct() public deprecated
  • chunk() public deprecated
  • chunkWithKeys() public deprecated
  • 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

  • combine() public deprecated
  • compile() public deprecated
  • compileQuery() public

    Compile the Elasticsearch query.

  • contains() public deprecated
  • count() public

    Returns the total amount of hits for the query

  • countBy() public deprecated
  • countKeys() public deprecated
  • each() public deprecated
  • eagerLoaded() public

    Sets the query instance to be an eager loaded query. If no argument is passed, the current configured query _eagerLoaded value is returned.

  • every() public deprecated
  • extract() public deprecated
  • filter() public deprecated
  • 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.

  • firstMatch() public deprecated
  • 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.

  • groupBy() public deprecated
  • highlight() public

    Set the highlight options for the query.

  • indexBy() public deprecated
  • insert() public deprecated
  • isEagerLoaded() public

    Returns the current configured query _eagerLoaded value

  • isEmpty() public deprecated
  • last() public deprecated
  • lazy() public deprecated
  • limit() public

    Sets the maximum number of results to return for this query. This sets the size option for the Elasticsearch query.

  • listNested() public deprecated
  • map() public deprecated
  • 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.

  • match() public deprecated
  • max() public deprecated
  • median() public deprecated
  • min() public deprecated
  • nest() public deprecated
  • 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.

  • prepend() public deprecated
  • prependItem() public deprecated
  • 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.

  • reduce() public deprecated
  • reject() public deprecated
  • repository() public deprecated

    Set the default Table object that will be used by this query and form the FROM clause.

  • sample() public deprecated
  • 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 Table object that will be used by this query and form the FROM clause.

  • setResult() public

    Set the result set for a query.

  • shuffle() public deprecated
  • skip() public deprecated
  • some() public deprecated
  • sortBy() public deprecated
  • stopWhen() public deprecated
  • sumOf() public deprecated
  • take() public deprecated
  • takeLast() public deprecated
  • through() public deprecated
  • toArray() public

    Returns an array representation of the results after executing the query.

  • toList() public deprecated
  • transpose() public deprecated
  • unfold() public deprecated
  • unwrap() public deprecated
  • 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

  • zip() public deprecated
  • zipWith() public deprecated

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<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(mixed $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
$conditions

The list of conditions.

array $types optional

Not used, required to comply with QueryInterface.

Returns
$this
See Also
\Cake\ElasticSearch\Query::where()
\Cake\ElasticSearch\QueryBuilder

append() ¶ public

append(mixed $items): Cake\Collection\CollectionInterface
Parameters
mixed $items

The items to append

Returns
Cake\Collection\CollectionInterface
See Also
\Cake\Collection\CollectionInterface::append()

appendItem() ¶ public

appendItem(mixed $item, mixed $key = null): Cake\Collection\CollectionInterface
Parameters
mixed $item

The item to apply

mixed $key optional

The key to append with

Returns
Cake\Collection\CollectionInterface
See Also
\Cake\Collection\CollectionInterface::appendItem()

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

avg() ¶ public

avg(callable|string|null $path = null): float|int|null
Parameters
callable|string|null $path optional

the path to average

Returns
float|int|null
See Also
\Cake\Collection\CollectionInterface::avg()

buffered() ¶ public

buffered(): Cake\Collection\CollectionInterface
Returns
Cake\Collection\CollectionInterface
See Also
\Cake\Collection\CollectionInterface::buffered()

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

cartesianProduct() ¶ public

cartesianProduct(callable|null $operation = null, callable|null $filter = null): Cake\Collection\CollectionInterface
Parameters
callable|null $operation optional

A callable that allows you to customize the product result.

callable|null $filter optional

A filtering callback that must return true for a result to be part of the final results.

Returns
Cake\Collection\CollectionInterface
See Also
\Cake\Collection\CollectionInterface::cartesianProduct()

chunk() ¶ public

chunk(int $chunkSize): Cake\Collection\CollectionInterface
Parameters
int $chunkSize

The maximum size for each chunk

Returns
Cake\Collection\CollectionInterface
See Also
\Cake\Collection\CollectionInterface::chunk()

chunkWithKeys() ¶ public

chunkWithKeys(int $chunkSize, bool $keepKeys = true): Cake\Collection\CollectionInterface
Parameters
int $chunkSize

The maximum size for each chunk

bool $keepKeys optional

If the keys of the array should be kept

Returns
Cake\Collection\CollectionInterface
See Also
\Cake\Collection\CollectionInterface::chunkWithKeys()

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(string|Elastica\Collapse $collapse): $this

Add collapse to the elastic query object

Parameters
string|Elastica\Collapse $collapse

Collapse field or elastic collapse object

Returns
$this

combine() ¶ public

combine(callable|string $keyPath, callable|string $valuePath, callable|string|null $groupPath = null): Cake\Collection\CollectionInterface
Parameters
callable|string $keyPath

The path for keys

callable|string $valuePath

The path for values

callable|string|null $groupPath optional

The path for grouping

Returns
Cake\Collection\CollectionInterface
See Also
\Cake\Collection\CollectionInterface::combine()

compile() ¶ public

compile(bool $keepKeys = true): Cake\Collection\CollectionInterface
Parameters
bool $keepKeys optional

Whether or not keys should be kept

Returns
Cake\Collection\CollectionInterface
See Also
\Cake\Collection\CollectionInterface::compile()

compileQuery() ¶ public

compileQuery(): Elastica\Query

Compile the Elasticsearch query.

Returns
Elastica\Query

contains() ¶ public

contains(mixed $value): bool
Parameters
mixed $value

The value to check.

Returns
bool
See Also
\Cake\Collection\CollectionInterface::contains()

count() ¶ public

count(): int

Returns the total amount of hits for the query

Returns
int

countBy() ¶ public

countBy(string|callable $path): Cake\Collection\CollectionInterface
Parameters
string|callable $path

The path to count by

Returns
Cake\Collection\CollectionInterface
See Also
\Cake\Collection\CollectionInterface::countBy()

countKeys() ¶ public

countKeys(): int
Returns
int
See Also
\Cake\Collection\CollectionInterface::countKeys()

each() ¶ public

each(callable $callback): Cake\Collection\CollectionInterface
Parameters
callable $callback

The callback to apply

Returns
Cake\Collection\CollectionInterface
See Also
\Cake\Collection\CollectionInterface::each()

eagerLoaded() ¶ public

eagerLoaded(bool $value): $this

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 $value

Whether to eager load.

Returns
$this

every() ¶ public

every(callable $callback): bool
Parameters
callable $callback

The callback to apply

Returns
bool
See Also
\Cake\Collection\CollectionInterface::every()

extract() ¶ public

extract(callable|string $path): Cake\Collection\CollectionInterface
Parameters
callable|string $path

The path to extract

Returns
Cake\Collection\CollectionInterface
See Also
\Cake\Collection\CollectionInterface::extract()

filter() ¶ public

filter(?callable $callback = null): Cake\Collection\CollectionInterface
Parameters
?callable $callback optional

The callback to apply

Returns
Cake\Collection\CollectionInterface
See Also
\Cake\Collection\CollectionInterface::filter()

find() ¶ public

find(string $finder = 'all', array<string, mixed> $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<string, mixed> $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

firstMatch() ¶ public

firstMatch(array $conditions): mixed
Parameters
array $conditions

The conditions to apply

Returns
mixed
See Also
\Cake\Collection\CollectionInterface::firstMatch()

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

Usually the query instance received by the formatter callback is the same query instance on which the callback was attached to, except for in a joined association, in that case the callback will be invoked on the association source side query, and it will receive that query instance instead of the one on which the callback was originally attached to - see the examples below!

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

Add a new column to the results with respect to the query's hydration configuration:

$query->formatResults(function ($results, $query) {
    return $results->map(function ($row) use ($query) {
        $data = [
            'bar' => 'baz',
        ];

if ($query->isHydrationEnabled()) {
            $row['foo'] = new Foo($data)
        } else {
            $row['foo'] = $data;
        }

return $row;
    });
});

Retaining access to the association target query instance of joined associations, by inheriting the contain callback's query argument:

// Assuming a `Articles belongsTo Authors` association that uses the join strategy

$articlesQuery->contain('Authors', function ($authorsQuery) {
    return $authorsQuery->formatResults(function ($results, $query) use ($authorsQuery) {
        // Here `$authorsQuery` will always be the instance
        // where the callback was attached to.

// The instance passed to the callback in the second
        // argument (`$query`), will be the one where the
        // callback is actually being applied to, in this
        // example that would be `$articlesQuery`.

// ...

return $results;
    });
});
Parameters
callable|null $formatter optional

The formatting callable.

int|bool $mode optional

Whether to overwrite, append or prepend the formatter.

Returns
$this
Throws
InvalidArgumentException

getIterator() ¶ public

getIterator(): Cake\Datasource\ResultSetInterface

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
Cake\Datasource\ResultSetInterface

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
\Cake\Datasource\QueryInterface::applyOptions() to read about the options that will be processed by this class and not returned by this function
applyOptions()

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<callable>

Returns the list of previously registered format routines.

Returns
array<callable>

groupBy() ¶ public

groupBy(callable|string $path): Cake\Collection\CollectionInterface
Parameters
callable|string $path

The path to group by

Returns
Cake\Collection\CollectionInterface
See Also
\Cake\Collection\CollectionInterface::groupBy()

highlight() ¶ public

highlight(array $highlight): $this

Set the highlight options for the query.

Parameters
array $highlight

The highlight options to use.

Returns
$this

indexBy() ¶ public

indexBy(string|callable $path): Cake\Collection\CollectionInterface
Parameters
string|callable $path

The path to extract

Returns
Cake\Collection\CollectionInterface
See Also
\Cake\Collection\CollectionInterface::indexBy()

insert() ¶ public

insert(string $path, mixed $values): Cake\Collection\CollectionInterface
Parameters
string $path

The path to insert on

mixed $values

The values to insert.

Returns
Cake\Collection\CollectionInterface
See Also
\Cake\Collection\CollectionInterface::insert()

isEagerLoaded() ¶ public

isEagerLoaded(): bool

Returns the current configured query _eagerLoaded value

Returns
bool

isEmpty() ¶ public

isEmpty(): bool
Returns
bool
See Also
\Cake\Collection\CollectionInterface::isEmpty()

last() ¶ public

last(): mixed
Returns
mixed
See Also
\Cake\Collection\CollectionInterface::last()

lazy() ¶ public

lazy(): Cake\Collection\CollectionInterface
Returns
Cake\Collection\CollectionInterface
See Also
\Cake\Collection\CollectionInterface::lazy()

limit() ¶ public

limit(Cake\Database\ExpressionInterface|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
Cake\Database\ExpressionInterface|int|null $limit

The number of documents to return.

Returns
$this

listNested() ¶ public

listNested(string|int $order = 'desc', callable|string $nestingKey = 'children'): Cake\Collection\CollectionInterface
Parameters
string|int $order optional

The order in which to return the elements

callable|string $nestingKey optional

The key name under which children are nested

Returns
Cake\Collection\CollectionInterface
See Also
\Cake\Collection\CollectionInterface::listNested()

map() ¶ public

map(callable $callback): Cake\Collection\CollectionInterface
Parameters
callable $callback

The callback to apply

Returns
Cake\Collection\CollectionInterface
See Also
\Cake\Collection\CollectionInterface::map()

mapReduce() ¶ public

mapReduce(callable|null $mapper = null, callable|null $reducer = null, bool $overwrite = false): $this

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 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
See Also
\Cake\Collection\Iterator\MapReduce for details on how to use emit data to the map reducer.

match() ¶ public

match(array $conditions): Cake\Collection\CollectionInterface
Parameters
array $conditions

The conditions to use.

Returns
Cake\Collection\CollectionInterface
See Also
\Cake\Collection\CollectionInterface::match()

max() ¶ public

max(callable|string $path, int $sort = \SORT_NUMERIC): mixed
Parameters
callable|string $path

The path to max

int $sort optional

The SORT_ constant to order by.

Returns
mixed
See Also
\Cake\Collection\CollectionInterface::max()

median() ¶ public

median(callable|string|null $path = null): float|int|null
Parameters
callable|string|null $path optional

the path to average

Returns
float|int|null
See Also
\Cake\Collection\CollectionInterface::median()

min() ¶ public

min(callable|string $path, int $sort = \SORT_NUMERIC): mixed
Parameters
callable|string $path

The path to max

int $sort optional

The SORT_ constant to order by.

Returns
mixed
See Also
\Cake\Collection\CollectionInterface::min()

nest() ¶ public

nest(callable|string $idPath, callable|string $parentPath, string $nestingKey = 'children'): Cake\Collection\CollectionInterface
Parameters
callable|string $idPath

The path to ids

callable|string $parentPath

The path to parents

string $nestingKey optional

Key used for nesting children.

Returns
Cake\Collection\CollectionInterface
See Also
\Cake\Collection\CollectionInterface::nest()

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
\Cake\ElasticSearch\Query::where()

prepend() ¶ public

prepend(mixed $items): Cake\Collection\CollectionInterface
Parameters
mixed $items

The items to prepend.

Returns
Cake\Collection\CollectionInterface
See Also
\Cake\Collection\CollectionInterface::prepend()

prependItem() ¶ public

prependItem(mixed $item, mixed $key = null): Cake\Collection\CollectionInterface
Parameters
mixed $item

The item to prepend

mixed $key optional

The key to use.

Returns
Cake\Collection\CollectionInterface
See Also
\Cake\Collection\CollectionInterface::prependItem()

queryMust() ¶ public

queryMust(array|callable|Elastica\Query\AbstractQuery $conditions, bool $overwrite = false): Cake\ElasticSearch\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
Cake\ElasticSearch\Query

queryShould() ¶ public

queryShould(array|callable|Elastica\Query\AbstractQuery $conditions, bool $overwrite = false): Cake\ElasticSearch\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
Cake\ElasticSearch\Query

reduce() ¶ public

reduce(callable $callback, mixed $initial = null): mixed
Parameters
callable $callback

The callback to apply

mixed $initial optional

The initial value

Returns
mixed
See Also
\Cake\Collection\CollectionInterface::reduce()

reject() ¶ public

reject(callable $callback): Cake\Collection\CollectionInterface
Parameters
callable $callback

The callback to apply

Returns
Cake\Collection\CollectionInterface
See Also
\Cake\Collection\CollectionInterface::reject()

repository() ¶ public

repository(Cake\Datasource\RepositoryInterface $repository): $this

Set the default Table object that will be used by this query and form the FROM clause.

Parameters
Cake\Datasource\RepositoryInterface $repository

The default table object to use

Returns
$this

sample() ¶ public

sample(int $length = 10): Cake\Collection\CollectionInterface
Parameters
int $length optional

The number of samples to select

Returns
Cake\Collection\CollectionInterface
See Also
\Cake\Collection\CollectionInterface::sample()

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(Cake\Database\ExpressionInterface|Cake\ORM\Association|Cake\ORM\Table|callable|array|string $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
Cake\Database\ExpressionInterface|Cake\ORM\Association|Cake\ORM\Table|callable|array|string $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|Cake\ORM\Table $repository): $this

Set the default Table object that will be used by this query and form the FROM clause.

Parameters
Cake\Datasource\RepositoryInterface|Cake\ORM\Table $repository

The default table object to use

Returns
$this

setResult() ¶ public

setResult(iterable $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
iterable $results

The results this query should return.

Returns
$this

shuffle() ¶ public

shuffle(): Cake\Collection\CollectionInterface
Returns
Cake\Collection\CollectionInterface
See Also
\Cake\Collection\CollectionInterface::shuffle()

skip() ¶ public

skip(int $length): Cake\Collection\CollectionInterface
Parameters
int $length

The number of items to skip

Returns
Cake\Collection\CollectionInterface
See Also
\Cake\Collection\CollectionInterface::skip()

some() ¶ public

some(callable $callback): bool
Parameters
callable $callback

The callback to apply

Returns
bool
See Also
\Cake\Collection\CollectionInterface::some()

sortBy() ¶ public

sortBy(callable|string $path, int $order = SORT_DESC, int $sort = \SORT_NUMERIC): Cake\Collection\CollectionInterface
Parameters
callable|string $path

the path to average

int $order optional

The \SORT_ constant for the direction you want results in.

int $sort optional

The \SORT_ method to use.

Returns
Cake\Collection\CollectionInterface
See Also
\Cake\Collection\CollectionInterface::sortBy()

stopWhen() ¶ public

stopWhen(callable|array $condition): Cake\Collection\CollectionInterface
Parameters
callable|array $condition

the method that will receive each of the elements and returns true when the iteration should be stopped.

Returns
Cake\Collection\CollectionInterface
See Also
\Cake\Collection\CollectionInterface::stopWhen()

sumOf() ¶ public

sumOf(string|callable $path = null): int|float
Parameters
string|callable $path optional

The path to sum

Returns
int|float
See Also
\Cake\Collection\CollectionInterface::sumOf()

take() ¶ public

take(int $length = 1, int $offset = 0): Cake\Collection\CollectionInterface
Parameters
int $length optional

The number of elements to take

int $offset optional

The offset of the first element to take.

Returns
Cake\Collection\CollectionInterface
See Also
\Cake\Collection\CollectionInterface::take()

takeLast() ¶ public

takeLast(int $length): Cake\Collection\CollectionInterface
Parameters
int $length

The number of items to take.

Returns
Cake\Collection\CollectionInterface
See Also
\Cake\Collection\CollectionInterface::takeLast()

through() ¶ public

through(callable $callback): Cake\Collection\CollectionInterface
Parameters
callable $callback

A callable function that will receive each of items in the collection.

Returns
Cake\Collection\CollectionInterface
See Also
\Cake\Collection\CollectionInterface::through()

toArray() ¶ public

toArray(): array

Returns an array representation of the results after executing the query.

Returns
array

toList() ¶ public

toList(): array
Returns
array
See Also
\Cake\Collection\CollectionInterface::toList()

transpose() ¶ public

transpose(): Cake\Collection\CollectionInterface
Returns
Cake\Collection\CollectionInterface
See Also
\Cake\Collection\CollectionInterface::transpose()

unfold() ¶ public

unfold(callable|null $callback = null): Cake\Collection\CollectionInterface
Parameters
callable|null $callback optional

A callable function that will receive each of items in the collection.

Returns
Cake\Collection\CollectionInterface
See Also
\Cake\Collection\CollectionInterface::unfold()

unwrap() ¶ public

unwrap(): Traversable
Returns
Traversable
See Also
\Cake\Collection\CollectionInterface::unwrap()

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
\Cake\ElasticSearch\QueryBuilder

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

zip() ¶ public

zip(iterable $items): Cake\Collection\CollectionInterface
Parameters
iterable $items

The collections to zip.

Returns
Cake\Collection\CollectionInterface
See Also
\Cake\Collection\CollectionInterface::zip()

zipWith() ¶ public

zipWith(iterable $items, callable $callback): Cake\Collection\CollectionInterface
Parameters
iterable $items

The collections to zip.

callable $callback

The function to use for zipping the elements together.

Returns
Cake\Collection\CollectionInterface
See Also
\Cake\Collection\CollectionInterface::zipWith()

Property Detail

$_cache ¶ protected

A query cacher instance if this query has caching enabled.

Type
Cake\Datasource\QueryCacher|null

$_dirty ¶ protected

Internal state to track whether or not the query has been modified.

Type
bool

$_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
array<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
iterable|null

$_searchOptions ¶ protected

Additional options for Elastica\Index::search()

Type
array
OpenHub
Pingping
Linode
  • Business Solutions
  • Showcase
  • Documentation
  • Book
  • API
  • Videos
  • Reporting Security Issues
  • Privacy Policy
  • Logos & Trademarks
  • Community
  • Get Involved
  • Issues (Github)
  • Bakery
  • Featured Resources
  • Training
  • Meetups
  • My CakePHP
  • CakeFest
  • Newsletter
  • Linkedin
  • YouTube
  • Facebook
  • Twitter
  • Mastodon
  • Help & Support
  • Forum
  • Stack Overflow
  • IRC
  • Slack
  • Paid Support

Generated using CakePHP API Docs