### Install Project Dependencies Source: https://github.com/babenkoivan/elastic-scout-driver/blob/master/CONTRIBUTING.md Run this command to install all necessary PHP dependencies for the project. ```bash composer install ``` -------------------------------- ### Run Test Suite and Setup Environment Source: https://github.com/babenkoivan/elastic-scout-driver/blob/master/CONTRIBUTING.md Execute this command to bring up the Docker environment and run all project tests. ```bash make up wait test ``` -------------------------------- ### Install Scout and Elastic Scout Driver Source: https://context7.com/babenkoivan/elastic-scout-driver/llms.txt Install the necessary packages via Composer. Publish Scout's configuration, and optionally the driver and client configurations. ```bash composer require laravel/scout babenkoivan/elastic-scout-driver php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider" php artisan vendor:publish --provider="Elastic\ScoutDriver\ServiceProvider" php artisan vendor:publish --provider="Elastic\Client\ServiceProvider" ``` -------------------------------- ### Install Elastic Scout Driver Source: https://github.com/babenkoivan/elastic-scout-driver/blob/master/README.md Install the Elastic Scout Driver using Composer. Ensure Laravel Scout is installed beforehand. ```bash composer require babenkoivan/elastic-scout-driver ``` ```bash composer require laravel/scout ``` -------------------------------- ### Install Packages via Composer Source: https://github.com/babenkoivan/elastic-scout-driver/wiki/Lumen-Installation Install the `elastic-scout-driver` and `laravel/scout` packages using Composer. ```bash composer require babenkoivan/elastic-scout-driver laravel/scout ``` -------------------------------- ### Lumen Installation: Helper Functions Source: https://context7.com/babenkoivan/elastic-scout-driver/llms.txt Adds missing helper functions like `config_path` and `resolve` required for Lumen compatibility. ```php // app/helpers.php basePath() . '/config' . ($path ? '/' . $path : $path); } } if (!function_exists('resolve')) { function resolve(string $name, array $parameters = []): mixed { return app($name, $parameters); } } ``` -------------------------------- ### Lumen Installation: Copy Config Files Source: https://context7.com/babenkoivan/elastic-scout-driver/llms.txt Manually copies configuration files to the config directory as Lumen does not support `artisan vendor:publish`. ```bash # Copy config files manually (no artisan vendor:publish in Lumen) mkdir config cp vendor/laravel/scout/config/scout.php config/scout.php cp vendor/babenkoivan/elastic-client/config/elastic.client.php config/elastic.client.php cp vendor/babenkoivan/elastic-scout-driver/config/elastic.scout_driver.php config/elastic.scout_driver.php ``` -------------------------------- ### Lumen Installation: Composer Autoload Source: https://context7.com/babenkoivan/elastic-scout-driver/llms.txt Configures composer.json to autoload the custom helper file in Lumen. ```json // composer.json — enable helpers autoload { "autoload": { "files": ["app/helpers.php"] } } ``` -------------------------------- ### Lumen Installation: Bootstrap App Configuration Source: https://context7.com/babenkoivan/elastic-scout-driver/llms.txt Registers Scout and Elastic Scout Driver service providers and configures the application instance in Lumen. ```php // bootstrap/app.php $app->instance('path.config', app()->basePath() . '/config'); $app->withEloquent(); $app->withFacades(); $app->register(Laravel\Scout\ScoutServiceProvider::class); $app->register(ElasticClient\ServiceProvider::class); $app->register(ElasticScoutDriver\ServiceProvider::class); ``` -------------------------------- ### Retrieve Raw Search Results Source: https://github.com/babenkoivan/elastic-scout-driver/blob/master/README.md Use the `raw()` method to get the raw `SearchResult` object from Elasticsearch. This provides access to more detailed information about the search results beyond the standard Scout collection. ```php $searchResult = App\Order::search('Star Trek')->raw(); ``` -------------------------------- ### Enable Immediate Refresh via .env Source: https://context7.com/babenkoivan/elastic-scout-driver/llms.txt Use the `.env` file to enable immediate document refresh for testing environments. ```bash # Enable immediate refresh for a test environment via .env ELASTIC_SCOUT_DRIVER_REFRESH_DOCUMENTS=true ``` -------------------------------- ### Create Config Directory Source: https://github.com/babenkoivan/elastic-scout-driver/wiki/Lumen-Installation Create a `config` directory in the root of your Lumen project if it does not already exist. ```bash mkdir config ``` -------------------------------- ### Enable helpers.php Autoload in composer.json Source: https://github.com/babenkoivan/elastic-scout-driver/wiki/Lumen-Installation Configure Composer to autoload the `app/helpers.php` file by adding it to the `files` section in your `composer.json`. ```json "autoload": { // ..., "files": [ "app/helpers.php" ] } ``` -------------------------------- ### Copy Configuration Files Source: https://github.com/babenkoivan/elastic-scout-driver/wiki/Lumen-Installation Copy the necessary configuration files for Laravel Scout, Elastic Client, and the Elastic Scout Driver into your project's `config` directory. ```bash cp vendor/laravel/scout/config/scout.php config/scout.php cp vendor/babenkoivan/elastic-client/config/elastic.client.php config/elastic.client.php cp vendor/babenkoivan/elastic-scout-driver/config/elastic.scout_driver.php config/elastic.scout_driver.php ``` -------------------------------- ### Publish Elastic Client Configuration Source: https://github.com/babenkoivan/elastic-scout-driver/blob/master/README.md Publish the configuration file for the elastic-client dependency. This allows customization of Elasticsearch client settings. ```bash php artisan vendor:publish --provider="Elastic\Client\ServiceProvider" ``` -------------------------------- ### Basic Model Search with Match All Query Source: https://github.com/babenkoivan/elastic-scout-driver/blob/master/README.md This snippet demonstrates a search that matches all documents when no specific query string is provided. It's useful for retrieving all records or applying filters without a text search. Ensure the model is configured for Scout. ```php $orders = App\Order::search()->where('user_id', 1)->get(); ``` -------------------------------- ### Register Container Bindings in bootstrap/app.php Source: https://github.com/babenkoivan/elastic-scout-driver/wiki/Lumen-Installation Register container bindings, including the configuration path instance and enabling Eloquent and Facades, within the `bootstrap/app.php` file. ```php $app->instance('path.config', app()->basePath() . '/config'); $app->withEloquent(); $app->withFacades(); ``` -------------------------------- ### Perform Static Code Analysis Source: https://github.com/babenkoivan/elastic-scout-driver/blob/master/CONTRIBUTING.md It is recommended to run static code analysis before submitting a Pull Request to catch potential issues. ```bash make static-analysis ``` -------------------------------- ### Register Service Providers in bootstrap/app.php Source: https://github.com/babenkoivan/elastic-scout-driver/wiki/Lumen-Installation Register the service providers for Laravel Scout, Elastic Client, and Elastic Scout Driver in the `bootstrap/app.php` file. ```php $app->register(Laravel\Scout\ScoutServiceProvider::class); $app->register(ElasticClient\ServiceProvider::class); $app->register(ElasticScoutDriver\ServiceProvider::class); ``` -------------------------------- ### Add Missing Helpers to app/helpers.php Source: https://github.com/babenkoivan/elastic-scout-driver/wiki/Lumen-Installation Define essential helper functions like `config_path` and `resolve` if they are not already present in your Lumen application. ```php basePath() . '/config' . ($path ? '/' . $path : $path); } } if (!function_exists('resolve')) { function resolve($name, array $parameters = []) { return app($name, $parameters); } } ``` -------------------------------- ### Basic Model Search with Query String Source: https://github.com/babenkoivan/elastic-scout-driver/blob/master/README.md Use this to perform a basic search on a model using Elasticsearch's query string syntax. Ensure the model is configured for Scout. ```php $orders = App\Order::search('title:(Star OR Trek)')->get(); ``` -------------------------------- ### Configure Scout Driver Source: https://github.com/babenkoivan/elastic-scout-driver/blob/master/README.md Update the 'driver' option in the Scout configuration file to 'elastic'. This directs Scout to use the Elastic Scout Driver. ```php 'driver' => env('SCOUT_DRIVER', 'elastic'), ``` -------------------------------- ### Publish Elastic Scout Driver Configuration Source: https://github.com/babenkoivan/elastic-scout-driver/blob/master/README.md Publish the configuration file for the Elastic Scout Driver itself. This enables the configuration of the 'refresh_documents' option. ```bash php artisan vendor:publish --provider="Elastic\ScoutDriver\ServiceProvider" ``` -------------------------------- ### Pagination with paginate() Source: https://context7.com/babenkoivan/elastic-scout-driver/llms.txt Implements pagination using Elasticsearch's from/size parameters, returning a LengthAwarePaginator. Supports custom page names and explicit page numbers. ```php $paginator = Client::search()->paginate(15); ``` ```php $paginator = Client::search('John') ->orderBy('phone_number') ->paginate( perPage: 2, pageName: 'p', page: 3 ); echo $paginator->perPage(); // => 2 echo $paginator->currentPage(); // => 3 echo $paginator->total(); // => 5 (total Elasticsearch hits) echo count($paginator->items()); // => items on this page ``` ```php foreach ($paginator->items() as $client) { echo $client->name; } echo $paginator->links(); // render pagination HTML ``` -------------------------------- ### Manual Indexing and Removal of Model Instances Source: https://context7.com/babenkoivan/elastic-scout-driver/llms.txt Manually add or remove model instances from the index without relying on Eloquent observer events. Supports single instances and collections. ```php // Index a single model $client = Client::find(1); $client->searchable(); // Index a collection of models Client::where('active', true)->searchable(); // Remove a single model from the index $client->unsearchable(); // Remove a collection from the index Client::where('active', false)->unsearchable(); // Import all models in batches (uses update() internally) // php artisan scout:import "App\Models\Client" ``` -------------------------------- ### Publish Scout Configuration Source: https://github.com/babenkoivan/elastic-scout-driver/blob/master/README.md Publish the Laravel Scout configuration file using an Artisan command. This allows you to modify Scout settings. ```bash php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider" ``` -------------------------------- ### Index Management with Engine::createIndex() / deleteIndex() Source: https://context7.com/babenkoivan/elastic-scout-driver/llms.txt Wraps the IndexManager to create and drop Elasticsearch indices directly or via Artisan commands. Note that changing the primary key name is not supported. ```php use Elastic\ScoutDriver\Engine; $engine = resolve(Engine::class); // Create a new index with the given name $engine->createIndex('clients'); // Internally: IndexManager::create(new Index('clients')) ``` ```php // Delete an index by name $engine->deleteIndex('clients'); // Internally: IndexManager::drop('clients') ``` ```php // Note: changing the primary key name is not supported and throws InvalidArgumentException try { $engine->createIndex('clients', ['primaryKey' => 'custom_id']); } catch (\\InvalidArgumentException $e) { echo $e->getMessage(); // "It is not possible to change the primary key name" } ``` ```php // Artisan equivalents: // php artisan scout:index clients // php artisan scout:delete-index clients ``` -------------------------------- ### Limiting Results with take() Source: https://context7.com/babenkoivan/elastic-scout-driver/llms.txt Sets the Elasticsearch size parameter to cap the number of results returned. Useful for retrieving top N items when combined with ordering. ```php $topFive = Client::search()->take(5)->get(); ``` ```php $topThree = Client::search('senior engineer') ->orderBy('rating', 'desc') ->take(3) ->get(); ``` -------------------------------- ### Perform Basic Full-Text Search Source: https://context7.com/babenkoivan/elastic-scout-driver/llms.txt Use `Model::search()` for full-text searches. It supports Elasticsearch's mini-language syntax and defaults to a `match_all` query if no string is provided. Returns an Eloquent Collection. ```php // Simple full-text search — returns an Eloquent Collection $clients = Client::search('John')->get(); // Mini-language syntax: OR, AND, field-specific queries $clients = Client::search('name:(John OR Matthew)')->get(); // Match-all search (no query string) — returns all indexed documents $allClients = Client::search()->get(); // Retrieve only the IDs of matching models (returns a plain Collection of keys) $ids = Client::search('John')->keys(); // => [1, 5, 12] // Raw search — returns Elastic\Adapter\Search\SearchResult directly $searchResult = Client::search('Star Trek')->raw(); echo $searchResult->total(); // => 42 // Search in a custom index (throws if index does not exist) $results = Client::search()->within('custom_index')->get(); ``` -------------------------------- ### Configure Elastic Scout Driver Refresh Source: https://context7.com/babenkoivan/elastic-scout-driver/llms.txt Control immediate document refresh after write operations in `config/elastic.scout_driver.php`. Set to `true` for testing, `false` (default) for production performance. ```php // config/elastic.scout_driver.php return [ // When true, Elasticsearch index is refreshed immediately after each write. // Default: false — rely on Elasticsearch's default refresh interval (1 second). 'refresh_documents' => env('ELASTIC_SCOUT_DRIVER_REFRESH_DOCUMENTS', false), ]; ``` -------------------------------- ### Soft Deletes Usage Source: https://context7.com/babenkoivan/elastic-scout-driver/llms.txt Demonstrates how to search for all, only soft-deleted, or include soft-deleted models using Scout's scopes. Soft-deleting flags documents, while forceDelete removes them. ```php // Soft-deleted models are excluded from normal search results Client::search()->get(); // only non-deleted ``` ```php // Include soft-deleted models explicitly Client::search()->withTrashed()->get(); ``` ```php // Only soft-deleted models Client::search()->onlyTrashed()->get(); ``` ```php // Hard-delete removes from DB and index $client->forceDelete(); ``` ```php // Soft-delete flags the document in Elasticsearch index $client->delete(); ``` -------------------------------- ### Soft Deletes Configuration Source: https://context7.com/babenkoivan/elastic-scout-driver/llms.txt Enables filtering of soft-deleted models in search results when 'scout.soft_delete' is set to true in the configuration. ```php 'soft_delete' => true, ``` -------------------------------- ### Perform PSR-2 Style Check Source: https://github.com/babenkoivan/elastic-scout-driver/blob/master/CONTRIBUTING.md Run this command to automatically check if your code adheres to the PSR-2 coding style standard. ```bash make style-check ``` -------------------------------- ### Lazy Collection with cursor() Source: https://context7.com/babenkoivan/elastic-scout-driver/llms.txt Streams model results as a LazyCollection for memory-efficient processing of large datasets. Processes models one at a time. ```php Client::search('active user') ->cursor() ->each(function (Client $client) { // process one model at a time $client->sendWelcomeEmail(); }); ``` -------------------------------- ### Flush All Documents from Model Index Source: https://context7.com/babenkoivan/elastic-scout-driver/llms.txt Deletes all documents from a model's index using a `match_all` query. Useful for resetting an index without dropping it. ```php // Remove all Client documents from Elasticsearch Client::removeAllFromSearch(); // Verify the index is empty $count = Client::search()->get()->count(); // => 0 // Artisan equivalent: // php artisan scout:flush "App\Models\Client" ``` -------------------------------- ### Ignoring Callback in Search Method Source: https://github.com/babenkoivan/elastic-scout-driver/blob/master/README.md The Elastic driver ignores the callback parameter in the `search` method to maintain compatibility with other Scout drivers and avoid exposing engine-specific implementations. Any closure provided will not be executed. ```php App\Order::search('Star Trek', function () { // this will not be triggered })->get() ``` -------------------------------- ### Override Search Parameters Factory Source: https://context7.com/babenkoivan/elastic-scout-driver/llms.txt Customizes how search parameters are constructed by binding a custom factory to the service container. This allows for modifications like adding custom highlight configurations. ```php // app/Providers/AppServiceProvider.php use Elastic\ScoutDriver\Factories\SearchParametersFactoryInterface; use App\Search\CustomSearchParametersFactory; public function register(): void { // Override only the search parameters factory $this->app->bind( SearchParametersFactoryInterface::class, CustomSearchParametersFactory::class ); } ``` ```php // app/Search/CustomSearchParametersFactory.php use Elastic\Adapter\Search\SearchParameters; use Elastic\ScoutDriver\Factories\SearchParametersFactory; use Laravel\Scout\Builder; class CustomSearchParametersFactory extends SearchParametersFactory { public function makeFromBuilder(Builder $builder, array $options = []): SearchParameters { $params = parent::makeFromBuilder($builder, $options); // Add a custom highlight configuration to every search $params->highlight([ 'fields' => ['name' => new \stdClass(), 'email' => new \stdClass()], ]); return $params; } } ``` -------------------------------- ### Make Eloquent Model Searchable Source: https://context7.com/babenkoivan/elastic-scout-driver/llms.txt Add the `Searchable` trait to your Eloquent model. Implement `toSearchableArray()` to define fields for indexing, excluding the primary key. Use `shouldBeSearchable()` to control document indexing. ```php toArray(), [$this->getKeyName()]); } /** * Optionally override to prevent indexing empty documents. */ public function shouldBeSearchable(): bool { return count($this->toSearchableArray()) > 0; } } ``` -------------------------------- ### Filtering with where(), whereIn(), whereNotIn() Source: https://context7.com/babenkoivan/elastic-scout-driver/llms.txt Adds Elasticsearch bool.filter clauses. Supports exact matches, inequality operators for range queries, and terms queries for inclusion/exclusion. ```php $clients = Client::search()->where('status', 'active')->get(); ``` ```php $adults = Client::search()->where('age', '>=', 18)->get(); ``` ```php $minors = Client::search()->where('age', '<', 18)->get(); ``` ```php $notAdmin = Client::search()->where('role', '!=', 'admin')->get(); ``` ```php $subset = Client::search()->whereIn('email', ['alice@example.com', 'bob@example.com'])->get(); ``` ```php $others = Client::search()->whereNotIn('email', ['alice@example.com'])->get(); ``` ```php $results = Client::search('developer') ->where('age', '>=', 25) ->whereIn('city', ['Berlin', 'London']) ->whereNotIn('status', ['banned']) ->get(); ``` -------------------------------- ### Sorting with orderBy() Source: https://context7.com/babenkoivan/elastic-scout-driver/llms.txt Adds Elasticsearch sort clauses. Multiple calls append to the sort array in order. Supports ascending and descending order. ```php $clients = Client::search()->orderBy('email')->get(); ``` ```php $clients = Client::search() ->orderBy('last_name', 'asc') ->orderBy('age', 'desc') ->get(); ``` ```php $results = Client::search('php developer') ->where('age', '>=', 21) ->orderBy('last_name', 'asc') ->get(); ``` -------------------------------- ### Control Searchability with shouldBeSearchable Source: https://github.com/babenkoivan/elastic-scout-driver/blob/master/README.md Override this method in your model to control whether a model instance should be indexed by Elasticsearch. This is useful to prevent indexing models that return an empty array from `toSearchableArray`. ```php public function shouldBeSearchable() { return count($this->toSearchableArray()) > 0; } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.