Download the PHP package phoenix-lib/elasticsearch-model without Composer
On this page you can find all versions of the php package phoenix-lib/elasticsearch-model. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download phoenix-lib/elasticsearch-model
More information about phoenix-lib/elasticsearch-model
Files in phoenix-lib/elasticsearch-model
Package elasticsearch-model
Short Description Laravel/Eloquent integration with Elasticsearch
License Apache-2.0
Informations about the package elasticsearch-model
datashaman/elasticsearch-model
Laravel-oriented implementation of elasticsearch-model.
Supports Laravel 5.4 and higher on PHP 7.0/7.1. PHP 7.2 will be supported and tested once Travis directly supports it.
Note that at least PHP 7.1 is required for Laravel 5.6+.
NB This is currently BETA quality software. Use on production at your own risk, and be aware that there might some further simplifications of the API in the next version or two.
The idea is to stay fairly faithful to the Ruby on Rails implementation, but housed in Laravel.
Installation
Install the package using composer:
composer require phoenix-lib/elasticsearch-model
Configure the service provider in config/app.php
:
Configure the alias in config.app.php
:
Copy base config into your applicatin:
php artisan vendor:publish --tag=config --provider='Datashaman\Elasticsearch\Model\ServiceProvider'
Edit config/elasticsearch.php
to your liking, setting ELASTICSEARCH_HOSTS
(comma-delimited definition of host:port) in .env
should cover most use cases.
Usage
Let's suppose you have an Article
model:
Setup
To add the Elasticsearch integration for this model, use the Datashaman\Elasticsearch\Model\ElasticsearchModel
trait in your class. You must also add a protected static $elasticsearch
property for storage:
This will extend the model with functionality related to Elasticsearch.
Proxy
The package contains a big amount of class and instance methods to provide all this functionality.
To prevent polluting your model namespace, nearly all functionality is accessed via static method Article::elasticsearch()
.
Elasticsearch client
The module will setup a client, connected to localhost:9200
, by default. You can access and use it like any other Elasticsearch::Client
:
To use a client with a different configuration, set a client for the model using Elasticsearch\ClientBuilder
:
Importing the data
The first thing you'll want to do is import your data to the index:
It's possible to import only records from a specific scope or query, transform the batch with the transform and preprocess options, or re-create the index by deleting it and creating it with correct mapping with the force option -- look for examples in the method documentation.
No errors were reported during importing, so... let's search the index!
Searching
For starters, we can try the simple type of search:
Search results
The returned response
object is a rich wrapper around the JSON returned from Elasticsearch, providing access to response metadata and the actual results (hits).
The response
object delegates to an internal LengthAwarePaginator
. You can get a Collection
via the delegate getCollection
method, althought the paginator also delegates mmethods to its Collection
so either of these work:
As you can see in the examples above, use the Collection::all()
method to get a regular array.
Each Elasticsearch hit is wrapped in the Result
class.
Result
has a dynamic getter:
- index, type, id, score and source are pulled from the top-level of the hit. e.g. index is hit[_index], type is hit[_type], etc
- if not one of the above, it looks for an existing item in the top-level hit. e.g. _version is hit[_version] (if defined)
- if not one of the above, it looks for an existing item in hit[_source] (the document). e.g. title is hit[_source][title] (if defined)
- if nothing resolves from above, it triggers a notice and returns null
It also has a toArray
method which returns the hit as an array.
Search results as database records
Instead of returning documents from Elasticsearch, the records method will return a collection of model instances, fetched from the primary database, ordered by score:
The returned object is a Collection
of model instances returned by your database, i.e. the Eloquent
instance.
The records method returns the real instances of your model, which is useful when you want to access your model methods - at the expense of slowing down your application, of course.
In most cases, working with results coming from Elasticsearch is sufficient, and much faster.
When you want to access both the database records
and search results
, use the eachWithHit
(or mapWithHit
) iterator:
Note the use Collection::all()
to convert to a regular array in the mapWithHit
example. Collection
methods prefer to return Collection
instances instead of regular arrays.
The first argument to records
is an options
array, the second argument is a callback which is passed the query builder to modify it on-the-fly. For example, to re-order the records differently to the results (from above):
Notice that adding an orderBy
call to the query overrides the ordering of the records, so that it is no longer the same as the results.
Searching multiple models
TODO Implement a Facade for cross-model searching.
Pagination
You can implement pagination with the from
and size
search parameters. However, search results can be automatically paginated much like Laravel does.
You have access to a length-aware paginator (the response delegates internally to the results()
call, so you don't need to call results() on the chain):
The rendered HTML was tidied up slightly for readability.
The Elasticsearch DSL
TODO Integrate this with a query builder.
Index Configuration
For proper search engine function, it's often necessary to configure the index properly. This package provides class methods to set up index settings and mappings.
You can use the defined settings and mappings to create an index with desired configuration:
There's a shortcut available for this common operation (convenient e.g. in tests):
By default, index name and document type will be inferred from your class name, you can set it explicitely, however:
Alternately, you can set them using the following static methods:
Updating the Documents in the Index
Usually, we need to update the Elasticsearch index when records in the database are created, updated or deleted; use the index_document, update_document and delete_document methods, respectively:
php use Datashaman\Elasticsearch\Model\ElasticsearchModel; use Datashaman\Elasticsearch\Model\Callbacks;
class Article { use ElasticsearchModel; use Callbacks; }
Article::first()->update([ 'title' => 'Updated!' ]);
Article::search('*')->map(function ($r) { return $r->title; }); => [ 'Updated!', 'Fast black dogs', 'Swift green Frogs' ]
The automatic callback on record update keeps track of changes in your model (via Laravel's `getDirty` implementation), and performs a partial update when this support is available.
The automatic callbacks are implemented in database adapters coming with this package. You can easily implement your own adapter: please see the relevant chapter below.
### Custom Callbacks
In case you would need more control of the indexing process, you can implement these callbacks yourself, by hooking into `created`, `saved`, `updated` or `deleted` events:
Regrettably there are no `committed` events in `Eloquent` like in Ruby's `ActiveRecord`.
### Asychronous Callbacks
Of course, you're still performing an HTTP request during your database transaction, which is not optimal for large-scale applications. A better option would be to process the index operations in background, with Laravel's `Queue` facade:
An example implementation of the `Indexer` class could look like this (source included in package):
## Model Serialization
By default, the model instance will be serialized to JSON using the output of the `toIndexedArray` method, which is defined automatically by the package:
If you want to customize the serialization, just implement the `toIndexedArray` method yourself, for instance with the `toArray` method:
The re-defined method will be used in the indexing methods, such as `indexDocument`.
## Attribution
Original design from [elasticsearch-model](https://github.com/elastic/elasticsearch-rails/tree/master/elasticsearch-model) which is:
* Copyright (c) 2014 Elasticsearch <http://www.elasticsearch.org>
* Licensed with Apache 2.0 license (detail in LICENSE.txt)
Changes include a rewrite of the core logic in PHP, as well as slight enhancements to accomodate Laravel and Eloquent.
## License
This package inherits the same license as its original. It is licensed under the Apache2 license, quoted below:
Copyright (c) 2016 datashaman <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
All versions of elasticsearch-model with dependencies
elasticsearch/elasticsearch Version >=2
illuminate/support Version >=5.4
laravel/helpers Version ^1.1