Plastic is an Elasticsearch ODM and mapper for Laravel. It renders the developer experience more enjoyable while using Elasticsearch, by providing a fluent syntax for mapping, querying, and storing eloquent models.
Installing Plastic
Run this command in the terminal via composer for the installation purpose:
composer require sleimanx2/plastic
If you are using Laravel >=5.5 the service provider will be automatically discovered otherwise we need to add the plastic service provider to config/app.php under the providers key:
Sleimanx2\Plastic\PlasticServiceProvider::class
This will create a config file at config/plastic.php and a mapping directory at database/mappings.
Defining Searchable Models
To get started, enable searching capabilities in your model by adding the Sleimanx2\Plastic\Searchable trait:
use Sleimanx2\Plastic\Searchable;
class Book extends Model
{
use Searchable;
}
Defining what data to store.
By default, Plastic will store all visible properties of your model, using $model->toArray().
In addition, Plastic provides you with two ways to manually specify which attributes/relations should be stored in Elasticsearch.
1 - Providing a searchable property to our model
public $searchable = ['id', 'name', 'body', 'tags', 'images'];
2 - Providing a buildDocument method
public function buildDocument()
{
return [
'id' => $this->id,
'tags' => $this->tags
];
}
Custom elastic type name
By the default, Plastic will use the model table name as the model type. You can customize it by adding a $documentType property to your model:
public $documentType = 'custom_type';
Custom elastic index name
By default, Plastic will use the index defined in the configuration file. You can customize in which index your model data will be stored by setting the $documentIndex property to your model:
public $documentIndex = 'custom_index';
Storing Model Content
Plastic automatically syncs model data with elastic when you save or delete your model from our SQL DB, however, this feature can be disabled by adding public $syncDocument = false to your model.
Available Methods:
- Saving a document
- Partial updating of a document
- Deleting a document
- Saving documents in bulk
- Deleting documents in bulk
Searching Model Content
Available Methods:
- Pagination
- Bool Query
- Nested Query
This package has a lot of methods with code examples. If you want to dig more, You can visit its complete documentation on Github.