Class Index
Base class for index.
A index in elastic search is approximately equivalent to a table or collection in a relational datastore. This ODM maps each index to a class.
Constants
Property Summary
-
$_connection protected
Cake\ElasticSearch\Datasource\Connection
Connection instance
-
$_documentClass protected
string
The name of the class that represent a single document for this type
-
$_eventClass protected
string
Default class name for new event objects.
-
$_eventManager protected
Cake\Event\EventManagerInterface|null
Instance of the Cake\Event\EventManager this object is using to dispatch inner events.
-
$_name protected
string
The name of the Elasticsearch index this class represents
-
$_registryAlias protected
string
Registry key used to create this index object
-
$_rulesChecker protected
Cake\Datasource\RulesChecker
The domain rules to be applied to entities saved by this table
-
$_validatorClass protected
string
Validator class.
-
$_validators protected
array<Cake\Validation\Validator>
A list of validation objects indexed by name
-
$embeds protected
array
Collection of Embedded sub documents this type has.
-
$schema protected
Cake\ElasticSearch\Datasource\MappingSchema
The mapping schema for this type.
Method Summary
-
__construct() public
Constructor
-
buildRules() public
Returns a RulesChecker object after modifying the one that was supplied.
-
callFinder() public
Calls a finder method directly and applies it to the passed query, if no query is passed a new one will be created and returned
-
checkRules() public
Returns whether the passed entity complies with all the rules stored in the rules checker.
-
createValidator() protected
Creates a validator using a custom method inside your class.
-
defaultConnectionName() public static
The default connection name to inject when creating an instance.
-
delete() public
Delete a single entity.
-
deleteAll() public
Delete all matching records.
-
dispatchEvent() public
Wrapper for creating and dispatching events.
-
embedMany() public
Mark a property in documents of this type as list of embedded sub-documents.
-
embedOne() public
Mark a property in documents of this type as an embedded sub-document.
-
embedded() public
Get the list of embedded documents this type has.
-
exists() public
Returns true if there is any record in this repository matching the specified conditions.
-
find() public
Creates a new Query for this repository and applies some defaults based on the type of search that was selected.
-
findAll() public
Returns the query as passed
-
get() public
Returns a single record after finding it by its primary key, if no record is found this method throws an exception.
-
getAlias() public
Returns the type name.
-
getConnection() public
Returns the connection instance
-
getEntityClass() public
Returns the class used to hydrate documents for this index.
-
getEventManager() public
Returns the Cake\Event\EventManager manager instance for this object.
-
getName() public
Returns the index name
-
getRegistryAlias() public
Returns the index registry key used to create this instance.
-
getTable() public
Get the index name, as required by QueryTrait
-
getValidator() public
Returns the validation rules tagged with $name. It is possible to have multiple different named validation sets, this is useful when you need to use varying rules when saving from different routines in your system.
-
hasField() public
Check whether or not a field exists in the mapping.
-
hasValidator() public
Checks whether a validator has been set.
-
implementedEvents() public
Get the callbacks this Index is interested in.
-
initialize() public
Initialize a index instance. Called after the constructor.
-
marshaller() public
Get a marshaller for this Index instance.
-
newEmptyEntity() public
This creates a new entity object.
-
newEntities() public
Create a list of entities + associated entities from an array.
-
newEntity() public
Create a new entity + associated entities from an array.
-
patchEntities() public
Merges each of the elements passed in
$data
into the entities found in$entities
respecting the accessible fields configured on the entities. Merging is done by matching the primary key in each of the elements in$data
and$entities
. -
patchEntity() public
Merges the passed
$data
into$entity
respecting the accessible fields configured on the entity. Returns the same entity after being altered. -
query() public
Creates a new Query instance for this repository
-
rulesChecker() public
Returns the RulesChecker for this instance.
-
save() public
Persists an entity based on the fields that are marked as dirty and returns the same entity after a successful save or false in case of any error.
-
saveMany() public
Persists a list of entities based on the fields that are marked as dirty and returns the same entity after a successful save or false in case of any error. Triggers the
Model.beforeSave
andModel.afterSave
events.Options
checkRules
Defaults to true. Check deletion rules before deleting the record.routing
Defaults to null. If set, this is used as the routing key for storing the document.
-
schema() public
Get the mapping data from the index type.
-
setAlias() public
Sets the index alias.
-
setConnection() public
Sets the connection instance
-
setEntityClass() public
Sets the class used to hydrate documents for this index.
-
setEventManager() public
Returns the Cake\Event\EventManagerInterface instance for this object.
-
setName() public
Sets the index name
-
setRegistryAlias() public
Sets the index registry key used to create this index instance.
-
setValidator() public
This method stores a custom validator under the given name.
-
updateAll() public
Update all matching records.
-
validationDefault() public
Returns the default validator object. Subclasses can override this function to add a default validation set to the validator object.
-
validationMethodExists() protected
Checks if validation method exists.
Method Detail
__construct() ¶ public
__construct(array $config = [])
Constructor
Options
- connection: The Elastica instance.
- name: The name of the index. If this isn't set the name will be inferred from the class name.
- type: The name of type mapping used. If this ins't set, the type will be equal to 'name'.
- eventManager: Used to inject a specific eventmanager.
At the end of the constructor the Model.initialize
event will be triggered.
Parameters
-
array
$config optional The configuration options, see above.
buildRules() ¶ public
buildRules(Cake\Datasource\RulesChecker $rules): Cake\Datasource\RulesChecker
Returns a RulesChecker object after modifying the one that was supplied.
Subclasses should override this method in order to initialize the rules to be applied to entities saved by this instance.
Parameters
-
Cake\Datasource\RulesChecker
$rules The rules object to be modified.
Returns
Cake\Datasource\RulesChecker
callFinder() ¶ public
callFinder(string $type, Cake\ElasticSearch\Query $query, array $options = []): Cake\ElasticSearch\Query
Calls a finder method directly and applies it to the passed query, if no query is passed a new one will be created and returned
Parameters
-
string
$type name of the finder to be called
-
Cake\ElasticSearch\Query
$query The query object to apply the finder options to
-
array
$options optional List of options to pass to the finder
Returns
Cake\ElasticSearch\Query
Throws
BadMethodCallException
checkRules() ¶ public
checkRules(Cake\Datasource\EntityInterface $entity, string $operation = RulesChecker::CREATE, ArrayObject|array|null $options = null): bool
Returns whether the passed entity complies with all the rules stored in the rules checker.
Parameters
-
Cake\Datasource\EntityInterface
$entity The entity to check for validity.
-
string
$operation optional The operation being run. Either 'create', 'update' or 'delete'.
-
ArrayObject|array|null
$options optional The options To be passed to the rules.
Returns
bool
createValidator() ¶ protected
createValidator(string $name): Cake\Validation\Validator
Creates a validator using a custom method inside your class.
This method is used only to build a new validator and it does not store it in your object. If you want to build and reuse validators, use getValidator() method instead.
Parameters
-
string
$name The name of the validation set to create.
Returns
Cake\Validation\Validator
Throws
RuntimeException
defaultConnectionName() ¶ public static
defaultConnectionName(): string
The default connection name to inject when creating an instance.
Returns
string
delete() ¶ public
delete(Cake\Datasource\EntityInterface $entity, ArrayAccess|array $options = []): bool
Delete a single entity.
Deletes an entity and possibly related associations from the database based on the 'dependent' option used when defining the association.
Triggers the Model.beforeDelete
and Model.afterDelete
events.
Parameters
-
Cake\Datasource\EntityInterface
$entity The entity to remove.
-
ArrayAccess|array
$options optional The options for the delete.
Returns
bool
deleteAll() ¶ public
deleteAll(mixed $conditions): int
Delete all matching records.
Deletes all records matching the provided conditions.
This method will not trigger beforeDelete/afterDelete events. If you need those first load a collection of records and delete them.
Parameters
-
mixed
$conditions An array of conditions, similar to those used with find()
Returns
int
See Also
dispatchEvent() ¶ public
dispatchEvent(string $name, array|null $data = null, object|null $subject = null): Cake\Event\EventInterface
Wrapper for creating and dispatching events.
Returns a dispatched event.
Parameters
-
string
$name Name of the event.
-
array|null
$data optional Any value you wish to be transported with this event to it can be read by listeners.
-
object|null
$subject optional The object that this event applies to ($this by default).
Returns
Cake\Event\EventInterface
embedMany() ¶ public
embedMany(string $name, array $options = []): void
Mark a property in documents of this type as list of embedded sub-documents.
Embedded documents are converted into instances of the named document type. This allows you to attach entity level behavior to subsections of your documents.
This method will make a list of embedded documents from the named property.
Parameters
-
string
$name The name of the property that contains the embedded document.
-
array
$options optional The options for the embedded document.
Returns
void
embedOne() ¶ public
embedOne(string $name, array $options = []): void
Mark a property in documents of this type as an embedded sub-document.
Embedded documents are converted into instances of the named document type. This allows you to attach entity level behavior to subsections of your documents.
Parameters
-
string
$name The name of the property that contains the embedded document.
-
array
$options optional The options for the embedded document.
Returns
void
embedded() ¶ public
embedded(): array
Get the list of embedded documents this type has.
Returns
array
exists() ¶ public
exists(array $conditions): bool
Returns true if there is any record in this repository matching the specified conditions.
Parameters
-
array
$conditions list of conditions to pass to the query
Returns
bool
find() ¶ public
find(string $type = 'all', array $options = []): Cake\ElasticSearch\Query
Creates a new Query for this repository and applies some defaults based on the type of search that was selected.
Model.beforeFind event
Each find() will trigger a Model.beforeFind
event for all attached
listeners. Any listener can set a valid result set using $query
Parameters
-
string
$type optional the type of query to perform
-
array
$options optional An array that will be passed to Query::applyOptions
Returns
Cake\ElasticSearch\Query
findAll() ¶ public
findAll(Cake\ElasticSearch\Query $query, array $options = []): Cake\ElasticSearch\Query
Returns the query as passed
Parameters
-
Cake\ElasticSearch\Query
$query An Elasticsearch query object
-
array
$options optional An array of options to be used for query logic
Returns
Cake\ElasticSearch\Query
get() ¶ public
get(mixed $primaryKey, array $options = []): Cake\ElasticSearch\Document
Returns a single record after finding it by its primary key, if no record is found this method throws an exception.
Any key present in the options array will be translated as a GET argument when getting the document by its id. This is often useful whe you need to specify the parent or routing.
This method will not trigger the Model.beforeFind callback as it does not use queries for the search, but a faster key lookup to the search index.
Parameters
-
mixed
$primaryKey The document's primary key
-
array
$options optional An array of options
Returns
Cake\ElasticSearch\Document
Throws
Elastica\Exception\NotFoundException
if no document exist with such id
getConnection() ¶ public
getConnection(): Cake\ElasticSearch\Datasource\Connection
Returns the connection instance
Returns
Cake\ElasticSearch\Datasource\Connection
getEntityClass() ¶ public
getEntityClass(): string
Returns the class used to hydrate documents for this index.
Returns
string
getEventManager() ¶ public
getEventManager(): Cake\Event\EventManagerInterface
Returns the Cake\Event\EventManager manager instance for this object.
You can use this instance to register any new listeners or callbacks to the object events, or create your own events and trigger them at will.
Returns
Cake\Event\EventManagerInterface
getName() ¶ public
getName(): string
Returns the index name
If this isn't set the name will be inferred from the class name
Returns
string
getRegistryAlias() ¶ public
getRegistryAlias(): string
Returns the index registry key used to create this instance.
Returns
string
getTable() ¶ public
getTable(): string
Get the index name, as required by QueryTrait
This method is just an alias of name().
Returns
string
getValidator() ¶ public
getValidator(string|null $name = null): Cake\Validation\Validator
Returns the validation rules tagged with $name. It is possible to have multiple different named validation sets, this is useful when you need to use varying rules when saving from different routines in your system.
If a validator has not been set earlier, this method will build a valiator using a method inside your class.
For example, if you wish to create a validation set called 'forSubscription', you will need to create a method in your Table subclass as follows:
public function validationForSubscription($validator)
{
return $validator
->add('email', 'valid-email', ['rule' => 'email'])
->add('password', 'valid', ['rule' => 'notBlank'])
->requirePresence('username');
}
$validator = $this->getValidator('forSubscription');
You can implement the method in validationDefault
in your Table subclass
should you wish to have a validation set that applies in cases where no other
set is specified.
If a $name argument has not been provided, the default validator will be returned.
You can configure your default validator name in a DEFAULT_VALIDATOR
class constant.
Parameters
-
string|null
$name optional The name of the validation set to return.
Returns
Cake\Validation\Validator
hasField() ¶ public
hasField(string $field): bool
Check whether or not a field exists in the mapping.
Parameters
-
string
$field The field to check.
Returns
bool
hasValidator() ¶ public
hasValidator(string $name): bool
Checks whether a validator has been set.
Parameters
-
string
$name The name of a validator.
Returns
bool
implementedEvents() ¶ public
implementedEvents(): array
Get the callbacks this Index is interested in.
By implementing the conventional methods a Index class is assumed to be interested in the related event.
Override this method if you need to add non-conventional event listeners. Or if you want your index to listen to non-standard events.
The conventional method map is:
- Model.beforeMarshal => beforeMarshal
- Model.beforeFind => beforeFind
- Model.beforeSave => beforeSave
- Model.afterSave => afterSave
- Model.beforeDelete => beforeDelete
- Model.afterDelete => afterDelete
- Model.beforeRules => beforeRules
- Model.afterRules => afterRules
Returns
array
initialize() ¶ public
initialize(array $config): void
Initialize a index instance. Called after the constructor.
You can use this method to define embedded documents, define validation and do any other initialization logic you need.
public function initialize(array $config)
{
$this->embedMany('Comments');
}
Parameters
-
array
$config Configuration options passed to the constructor
Returns
void
marshaller() ¶ public
marshaller(): Cake\ElasticSearch\Marshaller
Get a marshaller for this Index instance.
Returns
Cake\ElasticSearch\Marshaller
newEmptyEntity() ¶ public
newEmptyEntity(): Cake\Datasource\EntityInterface
This creates a new entity object.
Careful: This does not trigger any field validation. This entity can be persisted without validation error as empty record. Always patch in required fields before saving.
Returns
Cake\Datasource\EntityInterface
newEntities() ¶ public
newEntities(array $data, array<string, mixed> $options = []): array
Create a list of entities + associated entities from an array.
This is most useful when hydrating request data back into entities. For example, in your controller code:
$articles = $this->Articles->newEntities($this->request->data());
The hydrated entities can then be iterated and saved.
Parameters
-
array
$data The data to build an entity with.
-
array<string, mixed>
$options optional A list of options for the objects hydration.
Returns
array
newEntity() ¶ public
newEntity(array $data, array<string, mixed> $options = []): Cake\Datasource\EntityInterface
Create a new entity + associated entities from an array.
This is most useful when hydrating request data back into entities. For example, in your controller code:
$article = $this->Articles->newEntity($this->request->data());
The hydrated entity will correctly do an insert/update based on the primary key data existing in the database when the entity is saved. Until the entity is saved, it will be a detached record.
Parameters
-
array
$data The data to build an entity with.
-
array<string, mixed>
$options optional A list of options for the object hydration.
Returns
Cake\Datasource\EntityInterface
patchEntities() ¶ public
patchEntities(array|Traversable $entities, array $data, array<string, mixed> $options = []): array
Merges each of the elements passed in $data
into the entities
found in $entities
respecting the accessible fields configured on the entities.
Merging is done by matching the primary key in each of the elements in $data
and $entities
.
This is most useful when editing a list of existing entities using request data:
$article = $this->Articles->patchEntities($articles, $this->request->data());
Parameters
-
array|Traversable
$entities the entities that will get the data merged in
-
array
$data list of arrays to be merged into the entities
-
array<string, mixed>
$options optional A list of options for the objects hydration.
Returns
array
patchEntity() ¶ public
patchEntity(Cake\Datasource\EntityInterface $entity, array $data, array<string, mixed> $options = []): Cake\Datasource\EntityInterface
Merges the passed $data
into $entity
respecting the accessible
fields configured on the entity. Returns the same entity after being
altered.
This is most useful when editing an existing entity using request data:
$article = $this->Articles->patchEntity($article, $this->request->data());
Parameters
-
Cake\Datasource\EntityInterface
$entity the entity that will get the data merged in
-
array
$data key value list of fields to be merged into the entity
-
array<string, mixed>
$options optional A list of options for the object hydration.
Returns
Cake\Datasource\EntityInterface
query() ¶ public
query(): Cake\ElasticSearch\Query
Creates a new Query instance for this repository
Returns
Cake\ElasticSearch\Query
rulesChecker() ¶ public
rulesChecker(): Cake\Datasource\RulesChecker
Returns the RulesChecker for this instance.
A RulesChecker object is used to test an entity for validity on rules that may involve complex logic or data that needs to be fetched from relevant datasources.
Returns
Cake\Datasource\RulesChecker
See Also
save() ¶ public
save(Cake\Datasource\EntityInterface $entity, ArrayAccess|array $options = []): Cake\Datasource\EntityInterface|bool
Persists an entity based on the fields that are marked as dirty and returns the same entity after a successful save or false in case of any error.
Triggers the Model.beforeSave
and Model.afterSave
events.
Options
checkRules
Defaults to true. Check deletion rules before deleting the record.routing
Defaults to null. If set, this is used as the routing key for storing the document.
Parameters
-
Cake\Datasource\EntityInterface
$entity The entity to be saved
-
ArrayAccess|array
$options optional An array of options to be used for the event
Returns
Cake\Datasource\EntityInterface|bool
saveMany() ¶ public
saveMany(array $entities, array $options = []): bool
Persists a list of entities based on the fields that are marked as dirty and
returns the same entity after a successful save or false in case
of any error.
Triggers the Model.beforeSave
and Model.afterSave
events.
Options
checkRules
Defaults to true. Check deletion rules before deleting the record.routing
Defaults to null. If set, this is used as the routing key for storing the document.
Parameters
-
array
$entities An array of entities
-
array
$options optional An array of options to be used for the event
Returns
bool
schema() ¶ public
schema(): Cake\ElasticSearch\Datasource\MappingSchema
Get the mapping data from the index type.
This will fetch the schema from Elasticsearch the first time this method is called.
Returns
Cake\ElasticSearch\Datasource\MappingSchema
setAlias() ¶ public
setAlias(string $alias): $this
Sets the index alias.
Parameters
-
string
$alias Index alias
Returns
$this
setConnection() ¶ public
setConnection(Cake\ElasticSearch\Datasource\Connection $conn): $this
Sets the connection instance
Parameters
-
Cake\ElasticSearch\Datasource\Connection
$conn the new connection instance
Returns
$this
setEntityClass() ¶ public
setEntityClass(string $name): $this
Sets the class used to hydrate documents for this index.
Parameters
-
string
$name The name of the class to use
Returns
$this
Throws
Cake\ElasticSearch\Exception\MissingDocumentException
when the entity class cannot be found
setEventManager() ¶ public
setEventManager(Cake\Event\EventManagerInterface $eventManager): $this
Returns the Cake\Event\EventManagerInterface instance for this object.
You can use this instance to register any new listeners or callbacks to the object events, or create your own events and trigger them at will.
Parameters
-
Cake\Event\EventManagerInterface
$eventManager the eventManager to set
Returns
$this
setName() ¶ public
setName(string $name): $this
Sets the index name
Parameters
-
string
$name Index name
Returns
$this
setRegistryAlias() ¶ public
setRegistryAlias(string $registryAlias): $this
Sets the index registry key used to create this index instance.
Parameters
-
string
$registryAlias The key used to access this object.
Returns
$this
setValidator() ¶ public
setValidator(string $name, Cake\Validation\Validator $validator): $this
This method stores a custom validator under the given name.
You can build the object by yourself and store it in your object:
$validator = new \Cake\Validation\Validator();
$validator
->add('email', 'valid-email', ['rule' => 'email'])
->add('password', 'valid', ['rule' => 'notBlank'])
->allowEmpty('bio');
$this->setValidator('forSubscription', $validator);
Parameters
-
string
$name The name of a validator to be set.
-
Cake\Validation\Validator
$validator Validator object to be set.
Returns
$this
updateAll() ¶ public
updateAll(Cake\Database\Expression\QueryExpression|Closure|array|string $fields, mixed $conditions): int
Update all matching records.
Sets the $fields to the provided values based on $conditions. This method will not trigger beforeSave/afterSave events. If you need those first load a collection of records and update them.
Parameters
-
Cake\Database\Expression\QueryExpression|Closure|array|string
$fields A hash of field => new value.
-
mixed
$conditions An array of conditions, similar to those used with find()
Returns
int
validationDefault() ¶ public
validationDefault(Cake\Validation\Validator $validator): Cake\Validation\Validator
Returns the default validator object. Subclasses can override this function to add a default validation set to the validator object.
Parameters
-
Cake\Validation\Validator
$validator The validator that can be modified to add some rules to it.
Returns
Cake\Validation\Validator
validationMethodExists() ¶ protected
validationMethodExists(string $name): bool
Checks if validation method exists.
Parameters
-
string
$name Validation method name.
Returns
bool
Property Detail
$_documentClass ¶ protected
The name of the class that represent a single document for this type
Type
string
$_eventManager ¶ protected
Instance of the Cake\Event\EventManager this object is using to dispatch inner events.
Type
Cake\Event\EventManagerInterface|null
$_rulesChecker ¶ protected
The domain rules to be applied to entities saved by this table
Type
Cake\Datasource\RulesChecker
$_validators ¶ protected
A list of validation objects indexed by name
Type
array<Cake\Validation\Validator>
$schema ¶ protected
The mapping schema for this type.
Type
Cake\ElasticSearch\Datasource\MappingSchema