{"id":13396200,"url":"https://github.com/sleimanx2/plastic","last_synced_at":"2026-01-11T16:06:03.646Z","repository":{"id":55062887,"uuid":"58264395","full_name":"sleimanx2/plastic","owner":"sleimanx2","description":"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.","archived":false,"fork":false,"pushed_at":"2021-03-14T18:24:53.000Z","size":623,"stargazers_count":508,"open_issues_count":46,"forks_count":109,"subscribers_count":22,"default_branch":"master","last_synced_at":"2024-10-20T23:15:51.741Z","etag":null,"topics":["elasticsearch","laravel","php"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/sleimanx2.png","metadata":{"files":{"readme":"readme.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2016-05-07T12:09:58.000Z","updated_at":"2024-09-19T01:28:28.000Z","dependencies_parsed_at":"2022-08-14T10:40:43.165Z","dependency_job_id":null,"html_url":"https://github.com/sleimanx2/plastic","commit_stats":null,"previous_names":[],"tags_count":24,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sleimanx2%2Fplastic","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sleimanx2%2Fplastic/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sleimanx2%2Fplastic/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sleimanx2%2Fplastic/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/sleimanx2","download_url":"https://codeload.github.com/sleimanx2/plastic/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":221417349,"owners_count":16816866,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["elasticsearch","laravel","php"],"created_at":"2024-07-30T18:00:42.295Z","updated_at":"2026-01-11T16:06:03.620Z","avatar_url":"https://github.com/sleimanx2.png","language":"PHP","funding_links":[],"categories":["Popular Packages","PHP","Paquetes utiles"],"sub_categories":[],"readme":"![Plastic Logo](http://i.imgur.com/PyolY7g.png)\n\n\u003e 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.\n\n[![License](https://poser.pugx.org/laravel/framework/license.svg)](https://packagist.org/packages/sleimanx2/plastic) [![Build Status](https://travis-ci.org/sleimanx2/plastic.svg?branch=master\u0026\u0026refresh=2)](https://travis-ci.org/sleimanx2/plastic) [![StyleCI](https://styleci.io/repos/58264395/shield)](https://styleci.io/repos/58264395)\n\n\u003e This package is still under active development and may change.\n\n\u003e For Elasticsearch v2 please refer to version \u003c 0.4.0.\n\n# Installing Plastic\n\n```bash\ncomposer require sleimanx2/plastic\n```\n\nIf you are using **Laravel \u003e=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:\n\n```php\nSleimanx2\\Plastic\\PlasticServiceProvider::class\n```\n\nFinally we need to run:\n\n```bash\nphp artisan vendor:publish\n```\n\nThis will create a config file at `config/plastic.php` and a mapping directory at `database/mappings`.\n\n# Usage\n\n- [Defining Searchable Models](#searchable-models)\n- [Storing Model Content](#store-content)\n- [Searching](#searching)\n- [Aggregation](#aggregation)\n- [Suggestions](#suggestions)\n- [Mappings](#mappings)\n- [Populate An Index](#populate-an-index)\n- [Access The Client](#access-client)\n\n## [Defining Searchable Models]()\n\nTo get started, enable searching capabilities in your model by adding the `Sleimanx2\\Plastic\\Searchable` trait:\n\n```php\nuse Sleimanx2\\Plastic\\Searchable;\n\nclass Book extends Model\n{\n    use Searchable;\n}\n```\n\n### Defining what data to store.\n\nBy default, Plastic will store all visible properties of your model, using `$model-\u003etoArray()`.\n\nIn addition, Plastic provides you with two ways to manually specify which attributes/relations should be stored in Elasticsearch.\n\n#### 1 - Providing a searchable property to our model\n\n```php\npublic $searchable = ['id', 'name', 'body', 'tags', 'images'];\n```\n\n#### 2 - Providing a buildDocument method\n\n```php\npublic function buildDocument()\n{\n    return [\n        'id' =\u003e $this-\u003eid,\n        'tags' =\u003e $this-\u003etags\n    ];\n}\n```\n\n### Custom elastic type name\n\nBy 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:\n\n```php\npublic $documentType = 'custom_type';\n```\n\n### Custom elastic index name\n\nBy the 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:\n\n```php\npublic $documentIndex = 'custom_index';\n```\n\n## [Storing Model Content]()\n\nPlastic 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.\n\n\u003e Its important to note that manual document update should be performed in multiple scenarios:\n\n\u003e 1 - When you perform a bulk update or delete, no Eloquent event is triggered, therefore the document data won't be synced.\n\n\u003e 2 - Plastic doesn't listen to related models events (yet), so when you update a related model's content you should consider updating the parent document.\n\n### Saving a document\n\n```php\n$book = Book::first()-\u003edocument()-\u003esave();\n```\n\n### Partial updating a document\n\n```php\n$book = Book::first()-\u003edocument()-\u003eupdate();\n```\n\n### Deleting a document\n\n```php\n$book = Book::first()-\u003edocument()-\u003edelete();\n```\n\n### Saving documents in bulk\n\n```php\nPlastic::persist()-\u003ebulkSave(Tag::find(1)-\u003ebooks);\n```\n\n### Deleting documents in bulk\n\n```php\n$authors = Author::where('age','\u003e',25)-\u003eget();\n\nPlastic::persist()-\u003ebulkDelete($authors);\n```\n\n## [Searching Model Content]()\n\nPlastic provides a fluent syntax to query Elasticsearch which leads to compact readable code. Lets dig into it:\n\n```php\n$result = Book::search()-\u003ematch('title','pulp')-\u003eget();\n\n// Returns a collection of Book Models\n$books = $result-\u003ehits();\n\n// Returns the total number of matched documents\n$result-\u003etotalHits();\n\n// Returns the highest query score\n$result-\u003emaxScore();\n\n//Returns the time needed to execute the query\n$result-\u003etook();\n```\n\nTo get the raw DSL query that will be executed you can call `toDSL()`:\n\n```php\n$dsl = Book::search()-\u003ematch('title','pulp')-\u003etoDSL();\n```\n\n### Pagination\n\n```php\n$books = Book::search()\n    -\u003emultiMatch(['title', 'description'], 'ham on rye', ['fuzziness' =\u003e 'AUTO'])\n    -\u003esortBy('date')\n    -\u003epaginate();\n```\n\nYou can still access the result object after pagination using the result method:\n\n```php\n$books-\u003eresult();\n```\n\n### Bool Query\n\n```php\nUser::search()\n    -\u003emust()\n        -\u003eterm('name','kimchy')\n    -\u003emustNot()\n        -\u003erange('age',['from'=\u003e10,'to'=\u003e20])\n    -\u003eshould()\n        -\u003ematch('bio','developer')\n        -\u003ematch('bio','elastic')\n    -\u003efilter()\n        -\u003eterm('tag','tech')\n    -\u003eget();\n```\n\n### Nested Query\n\n```php\n$contain = 'foo';\n\nPost::search()\n    -\u003emultiMatch(['title', 'body'], $contain)\n    -\u003enested('tags', function (SearchBuilder $builder) use ($contain) {\n        $builder-\u003ematch('tags.name', $contain);\n    })-\u003eget();\n```\n\n\u003e Check out this [documentation](docs/search.md) of supported search queries within Plastic and how to apply unsupported queries.\n\n### Change index on the fly\n\nTo switch to a different index for a single query, simply use the `index` method.\n\n```php\n$result = Book::search()-\u003eindex('special-books')-\u003ematch('title','pulp')-\u003eget();\n```\n\n## [Aggregation]()\n\n```php\n$result = User::search()\n    -\u003ematch('bio', 'elastic')\n    -\u003eaggregate(function (AggregationBuilder $builder) {\n        $builder-\u003eaverage('average_age', 'age');\n    })-\u003eget();\n\n$aggregations = $result-\u003eaggregations();\n```\n\n\u003e Check out this [documentation](docs/aggregation.md) of supported aggregations within plastic and how to apply unsupported aggregations.\n\n## [Suggestions]()\n\n```php\nPlastic::suggest()-\u003ecompletion('tag_suggest', 'photo')-\u003eget();\n```\n\nThe suggestions query builder can also be accessed directly from the model as well:\n\n```php\n//this be handy if you have a custom index for your model\nTag::suggest()-\u003eterm('tag_term','admin')-\u003eget();\n```\n\n## [Model Mapping]()\n\nMappings are an important aspect of Elasticsearch. You can compare them to indexing in SQL databases. Mapping your models yields better and more efficient search results, and allows us to use some special query functions like nested fields and suggestions.\n\n### Generate a Model Mapping\n\n```bash\nphp artisan make:mapping \"App\\User\"\n```\n\nThe new mapping will be placed in your `database/mappings` directory.\n\n### Mapping Structure\n\nA mapping class contains a single method `map`. The map method is used to map the given model fields.\n\nWithin the `map` method you may use the Plastic Map builder to expressively create field maps. For example, let's look at a sample mapping that creates a Tag model map:\n\n```php\nuse Sleimanx2\\Plastic\\Map\\Blueprint;\nuse Sleimanx2\\Plastic\\Mappings\\Mapping;\n\nclass AppTag extends Mapping\n{\n    /**\n     * Full name of the model that should be mapped\n     *\n     * @var string\n     */\n    protected $model = App\\Tag::class;\n\n    /**\n     * Run the mapping.\n     *\n     * @return void\n     */\n    public function map()\n    {\n        Map::create($this-\u003egetModelType(), function (Blueprint $map) {\n            $map-\u003estring('name')-\u003estore('true')-\u003eindex('analyzed');\n\n            // instead of the fluent syntax we can use the second method argument to fill the attributes\n            $map-\u003ecompletion('suggestion', ['analyzer' =\u003e 'simple', 'search_analyzer' =\u003e 'simple']);\n        },$this-\u003egetModelIndex());\n    }\n}\n```\n\n\u003e To learn about all of the methods available on the Map builder, check out this [documentation](docs/mapping.md).\n\n### Run Mappings\n\nRunning the created mappings can be done using the Artisan console command:\n\n```bash\nphp artisan mapping:run\n```\n\n### Updating Mappings\n\nIf your update consists only of adding a new field mapping you can always update our model map with your new field and run:\n\n```bash\nphp artisan mapping:rerun\n```\n\nThe mapping for existing fields cannot be updated or deleted, so you'll need to use one of following techniques to update existing fields.\n\n#### 1 - Create a new index\n\nYou can always create a new Elasticsearch index and re-run the mappings. After running the mappings you can use the `bulkSave` method to sync your SQL data with Elasticsearch.\n\n#### 2 - Using aliases\n\nIts recommended to create your Elasticsearch index with an alias to ease the process of updating your model mappings with zero downtime. To learn more check out:\n\n\u003chttps://www.elastic.co/blog/changing-mapping-with-zero-downtime\u003e\n\n## [Populate An Index]()\n\nPopulating an index with searchable models can be done by running an Artisan console command :\n\n```bash\nphp artisan plastic:populate [--mappings][--index=...][--database=...]\n```\n\n- `--mappings` Create the models mappings before populating the index\n- `--database=...` Database connection to use for mappings instead of the default one\n- `--index=...` Index to populate instead of the default one\n\nThe list of models from which to recreate the documents has to be configured **per index** in `config/plastic.php`:\n```\n    'populate' =\u003e [\n        'models' =\u003e [\n            // Models for the default index\n            env('PLASTIC_INDEX', 'plastic') =\u003e [\n                App\\Models\\Article::class,\n                App\\Models\\Page::class,\n            ],\n            // Models for the index \"another_index\"\n            'another_index' =\u003e [\n                App\\Models\\User::class,\n            ],\n        ],\n    ],\n```\n\n## [Access The Client]()\n\nYou can access the Elasticsearch client to manage your indices and aliases as follows:\n\n```php\n$client = Plastic::getClient();\n\n//index delete\n$client-\u003eindices()-\u003edelete(['index'=\u003e Plastic::getDefaultIndex()]);\n//index create\n$client-\u003eindices()-\u003ecreate(['index' =\u003e Plastic::getDefaultIndex()]);\n```\n\nMore about the official elastic client : \u003chttps://github.com/elastic/elasticsearch-php\u003e\n\n# Contributing\n\nThank you for contributing, The contribution guide can be found [Here](CONTRIBUTING.md).\n\n# License\n\nPlastic is open-sourced software licensed under the [MIT license](LICENSE.md).\n\n# To Do\n\n## Search Query Builder\n\n- [ ] implement Boosting query\n- [ ] implement ConstantScore query\n- [ ] implement DisMaxQuery query\n- [ ] implement MoreLikeThis query (with raw eloquent models)\n- [ ] implement GeoShape query\n\n## Aggregation Query Builder\n\n- [ ] implement Nested aggregation\n- [ ] implement ExtendedStats aggregation\n- [ ] implement TopHits aggregation\n\n## Mapping\n\n- [ ] Find a seamless way to update field mappings with zero downtime with aliases\n\n## General\n\n- [ ] Better query builder documentation\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsleimanx2%2Fplastic","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsleimanx2%2Fplastic","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsleimanx2%2Fplastic/lists"}