Download the PHP package datashaman/elasticsearch-model without Composer

On this page you can find all versions of the php package datashaman/elasticsearch-model. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

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

Build Status StyleCI

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 datashaman/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:

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

PHP Build Version
Package Version
Requires php Version >=7.0
elasticsearch/elasticsearch Version >=2
illuminate/support Version >=5.4
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package datashaman/elasticsearch-model contains the following files

Loading the files please wait ....