イントロダクションIntroduction
Laravel Scout(Scout、斥候)は、Eloquentモデルへ、シンプルなドライバベースのフルテキストサーチを提供します。モデルオブサーバを使い、Scoutは検索インデックスを自動的にEloquentレコードと同期します。Laravel Scout[https://github.com/laravel/scout] provides a simple, driver-based solution for adding full-text search to your Eloquent models[/docs/{{version}}/eloquent]. Using model observers, Scout will automatically keep your search indexes in sync with your Eloquent records.
coutは組み込みのdatabaseエンジンを搭載しており、MySQL/PostgreSQLのフルテキストインデックスとLIKE句を使用して既存のデータベースを検索するため、外部サービスは必要ありません。ほとんどのアプリケーションでは、これで十分です。Laravelで使用できるすべての検索オプションの概要は、検索ドキュメントを参照してください。Scout ships with a built-in database engine that uses MySQL / PostgreSQL full-text indexes and LIKE clauses to search your existing database — no external service required. For most applications, this is all you need. For an overview of all search options available in Laravel, consult the search documentation[/docs/{{version}}/search].
Scoutには、タイポトレランス(打ち間違い許容)、ファセットフィルタリング、大規模なジオサーチなどの機能が必要な場合のために、Algolia、Meilisearch、Typesenseのドライバも用意しています。ローカル開発用の"collection"ドライバも利用でき、カスタムエンジンを自由に作成することさえも可能です。Scout also includes drivers for Algolia[https://www.algolia.com/], Meilisearch[https://www.meilisearch.com], and Typesense[https://typesense.org] when you need features like typo tolerance, faceted filtering, or geo-search at massive scale. A "collection" driver is also available for local development, and you are free to write custom engines[#custom-engines] as well.
インストールInstallation
最初に、Composerパッケージマネージャを使い、Scoutをインストールします。First, install Scout via the Composer package manager:
composer require laravel/scout
Scoutをインストールした後、vendor:publish Artisanコマンドを実行してScout設定ファイルをリソース公開する必要があります。このコマンドは、scout.php設定ファイルをアプリケーションのconfigディレクトリへリソース公開します。After installing Scout, you should publish the Scout configuration file using the vendor:publish Artisan command. This command will publish the scout.php configuration file to your application's config directory:
php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"
最後に、検索可能にしたいモデルにLaravel\Scout\Searchableトレイトを追加します。このトレイトは、モデルを検索ドライバと自動的に同期させるモデルオブザーバを登録します。Finally, add the Laravel\Scout\Searchable trait to the model you would like to make searchable. This trait will register a model observer that will automatically keep the model in sync with your search driver:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Laravel\Scout\Searchable;
class Post extends Model
{
use Searchable;
}
キュー投入Queueing
databaseまたはcollection以外のエンジンを使用する場合、ライブラリを使用する前にキュードライバの設定を考慮すべきです。キューワーカを実行することで、Scoutはモデル情報を検索インデックスに同期する全ての操作をキューに投入し、アプリケーションのWebインターフェイスのレスポンス時間を大幅に改善できます。When using an engine that is not the database or collection engine, you should strongly consider configuring a queue driver[/docs/{{version}}/queues] before using the library. Running a queue worker will allow Scout to queue all operations that sync your model information to your search indexes, providing much better response times for your application's web interface.
キュードライバを設定したら、config/scout.php設定ファイルのqueueオプションの値をtrueへ設定してください。Once you have configured a queue driver, set the value of the queue option in your config/scout.php configuration file to true:
'queue' => true,
queueオプションをfalseに設定している場合でも、AlgoliaやMeilisearchなどの一部のScoutドライバは、常に非同期でレコードをインデックスすることを忘れないでください。言い換えると、Laravelアプリケーション内でインデックス操作が完了しても、検索エンジン自体には、新しいレコードや更新したレコードがすぐに反映されない場合があります。Even when the queue option is set to false, it's important to remember that some Scout drivers like Algolia and Meilisearch always index records asynchronously. In other words, even though the index operation has completed within your Laravel application, the search engine itself may not reflect the new and updated records immediately.
Scoutジョブで使用する接続とキューを指定するには、queue設定オプションを配列で定義してください。To specify the connection and queue that your Scout jobs utilize, you may define the queue configuration option as an array:
'queue' => [
'connection' => 'redis',
'queue' => 'scout'
],
もちろん、Scoutジョブが利用するコネクションやキューをカスタマイズする場合は、そのコネクションやキューでジョブを処理するキューワーカを実行する必要があります。Of course, if you customize the connection and queue that Scout jobs utilize, you should run a queue worker to process jobs on that connection and queue:
php artisan queue:work redis --queue=scout
ドライバ動作要件Driver Prerequisites
AlgoliaAlgolia
Algoliaドライバを使用する場合、Algolia idとsecret接続情報をconfig/scout.php設定ファイルで設定する必要があります。接続情報を設定し終えたら、Algolia PHP SDKをComposerパッケージマネージャで、インストールする必要があります。When using the Algolia driver, you should configure your Algolia id and secret credentials in your config/scout.php configuration file. Once your credentials have been configured, you will also need to install the Algolia PHP SDK via the Composer package manager:
composer require algolia/algoliasearch-client-php
MeilisearchMeilisearch
Meilisearchは、高速なオープンソースの検索エンジンです。ローカルマシンにMeilisearchをインストールする方法がわからない場合は、Laravelの公式サポートのDocker開発環境であるLaravel Sailを利用できます。Meilisearch[https://www.meilisearch.com] is a fast, open source search engine. If you aren't sure how to install Meilisearch on your local machine, you may use Laravel Sail[/docs/{{version}}/sail#meilisearch], Laravel's officially supported Docker development environment.
Meilisearchドライバを使用する場合は、Composerパッケージマネージャを使用して、Meilisearch PHP SDKをインストールする必要があります。When using the Meilisearch driver you will need to install the Meilisearch PHP SDK via the Composer package manager:
composer require meilisearch/meilisearch-php http-interop/http-factory-guzzle
次に、アプリケーションの.envファイル内のSCOUT_DRIVER環境変数とMeilisearch hostとkey認証情報を設定します。Then, set the SCOUT_DRIVER environment variable as well as your Meilisearch host and key credentials within your application's .env file:
SCOUT_DRIVER=meilisearch
MEILISEARCH_HOST=http://127.0.0.1:7700
MEILISEARCH_KEY=masterKey
Meilisearchの詳細については、Meilisearchのドキュメントを参照してください。For more information regarding Meilisearch, please consult the Meilisearch documentation[https://docs.meilisearch.com/learn/getting_started/quick_start.html].
さらに、Meilisearchのバイナリ互換のドキュメントを見て、自分が使っているMeilisearchのバイナリバージョンと互換性のあるバージョンのmeilisearch/meilisearch-phpをインストールしてください。In addition, you should ensure that you install a version of meilisearch/meilisearch-php that is compatible with your Meilisearch binary version by reviewing Meilisearch's documentation regarding binary compatibility[https://github.com/meilisearch/meilisearch-php#-compatibility-with-meilisearch].
Warning! Meilisearchを利用しているアプリケーションのScoutをアップグレードする際には、常にMeilisearchサービス自体に追加の破壊的な変更がないか確認する必要があります。[!WARNING] When upgrading Scout on an application that utilizes Meilisearch, you should always review any additional breaking changes[https://github.com/meilisearch/Meilisearch/releases] to the Meilisearch service itself.
TypesenseTypesense
Typesenseは、光のように早いオープンソース検索エンジンで、キーワード検索、セマンティック検索、ジオ検索、ベクトル検索をサポートしています。Typesense[https://typesense.org] is a lightning-fast, open source search engine and supports keyword search, semantic search, geo search, and vector search.
Typesenseをセルフホストすることも、Typesense Cloudを利用することもできます。You can self-host[https://typesense.org/docs/guide/install-typesense.html#option-2-local-machine-self-hosting] Typesense or use Typesense Cloud[https://cloud.typesense.org].
ScoutでTypesenseを使用開始するには、Composerパッケージマネージャにより、Typesense PHP SDKをインストールします。To get started using Typesense with Scout, install the Typesense PHP SDK via the Composer package manager:
composer require typesense/typesense-php
次に、アプリケーションの.envファイルで、SCOUT_DRIVER環境変数と、TypesenseホストとAPIキーの認証情報を設定します。Then, set the SCOUT_DRIVER environment variable as well as your Typesense host and API key credentials within your application's .env file:
SCOUT_DRIVER=typesense
TYPESENSE_API_KEY=masterKey
TYPESENSE_HOST=localhost
Laravel Sailを使用している場合は、Dockerコンテナ名に合わせてTYPESENSE_HOST環境変数を調整する必要があるかもしれません。また、オプションでインストールのポート、パス、プロトコルを指定することもできます。If you are using Laravel Sail[/docs/{{version}}/sail], you may need to adjust the TYPESENSE_HOST environment variable to match the Docker container name. You may also optionally specify your installation's port, path, and protocol:
TYPESENSE_PORT=8108
TYPESENSE_PATH=
TYPESENSE_PROTOCOL=http
Typesenseコレクションの追加設定とスキーマ定義は、アプリケーションのconfig/scout.php設定ファイルにあります。Typesenseに関するより詳しい情報は、Typesenseドキュメントを参照してください。Additional settings and schema definitions for your Typesense collections can be found within your application's config/scout.php configuration file. For more information regarding Typesense, please consult the Typesense documentation[https://typesense.org/docs/guide/#quick-start].
設定Configuration
Searchableデータの設定Configuring Searchable Data
特定のモデルのtoArray形式のすべてをその検索インデックスへデフォルトで保存します。検索インデックスに同期するデータをカスタマイズしたい場合は、モデルのtoSearchableArrayメソッドをオーバーライドしてください。By default, the entire toArray form of a given model will be persisted to its search index. If you would like to customize the data that is synchronized to the search index, you may override the toSearchableArray method on the model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Laravel\Scout\Searchable;
class Post extends Model
{
use Searchable;
/**
* モデルのindexableなデータ配列を取得
*
* @return array<string, mixed>
*/
public function toSearchableArray(): array
{
$array = $this->toArray();
// データ配列のカスタマイズ…
return $array;
}
}
モデルエンジンの設定Configuring Model Engines
検索時、Scoutは通常、アプリケーションのscout設定ファイルで指定したデフォルトの検索エンジンを使用します。ただし、モデルのsearchableUsingメソッドをオーバーライドすれば、指定のモデル検索エンジンへ変更できます。When searching, Scout will typically use the default search engine specified in your application's scout configuration file. However, the search engine for a particular model can be changed by overriding the searchableUsing method on the model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Laravel\Scout\Engines\Engine;
use Laravel\Scout\Scout;
use Laravel\Scout\Searchable;
class User extends Model
{
use Searchable;
/**
* モデルのインデックスに使用するエンジンの取得
*/
public function searchableUsing(): Engine
{
return Scout::engine('meilisearch');
}
}
データベース/コレクションエンジンDatabase / Collection Engines
データベースエンジンDatabase Engine
Warning! データベースエンジンは現在、MySQLとPostgreSQLをサポートしており、両方とも高速なフルテキストカラムインデックスをサポートしています。[!WARNING] The database engine currently supports MySQL and PostgreSQL, both of which provide support for fast, full-text column indexing.
databaseエンジンは、MySQL/PostgreSQLのフルテキストインデックスとLIKE句を使用して、既存のデータベースを直接検索します。多くのアプリケーションにとって、これは検索を追加する最もシンプルで実用的な方法であり、外部サービスや追加のインフラストラクチャは必要ありません。The database engine uses MySQL / PostgreSQL full-text indexes and LIKE clauses to search your existing database directly. For many applications, this is the simplest and most practical way to add search — no external service or additional infrastructure required.
データベースエンジンを使用するには、環境変数SCOUT_DRIVERをdatabaseに設定してください。To use the database engine, set the SCOUT_DRIVER environment variable to database:
SCOUT_DRIVER=database
設定を完了したら、Searchableなデータを定義し、モデルに対して検索クエリの実行を使用開始できます。サードパーティのエンジンとは異なり、データベースエンジンは個別のインデックス作成ステップを必要とせず、データベーステーブルを直接検索します。Once configured, you may define your searchable data[#configuring-searchable-data] and start executing search queries[#searching] against your models. Unlike third-party engines, the database engine requires no separate indexing step — it searches your database tables directly.
データベース検索戦略のカスタマイズCustomizing Database Searching Strategies
デフォルトでは、データベースエンジンはSearchableとして設定したすべてのモデル属性に対してLIKEクエリを実行します。しかし、特定のカラムに対し、より効率的な検索戦略を割り当てることもできます。 SearchUsingFullText属性はそのカラムにデータベースのフルテキストインデックスを使用し、SearchUsingPrefixは文字列全体の中を検索(%example%)する代わりに、文字列の先頭(example%)のみを一致させます。By default, the database engine will execute a LIKE query against every model attribute that you have configured as searchable[#configuring-searchable-data]. However, you can assign more efficient search strategies to specific columns. The SearchUsingFullText attribute will use your database's full-text index for that column, while SearchUsingPrefix will only match the beginning of strings (example%) instead of searching within the entire string (%example%).
この動作を定義するには、モデルのtoSearchableArrayメソッドへPHP属性を割り当てます。属性のないカラムは、引き続きデフォルトのLIKE戦略を使用します。To define this behavior, assign PHP attributes to your model's toSearchableArray method. Any columns without an attribute will continue to use the default LIKE strategy:
use Laravel\Scout\Attributes\SearchUsingFullText;
use Laravel\Scout\Attributes\SearchUsingPrefix;
/**
* モデルのインデックス可能なデータ配列の取得
*
* @return array<string, mixed>
*/
#[SearchUsingPrefix(['id', 'email'])]
#[SearchUsingFullText(['bio'])]
public function toSearchableArray(): array
{
return [
'id' => $this->id,
'name' => $this->name,
'email' => $this->email,
'bio' => $this->bio,
];
}
Warning! カラムがフルテキストクエリ制約を使用するように指定する前に、そのカラムにフルテキストインデックスを確実に割り当ててください。[!WARNING] Before specifying that a column should use full text query constraints, ensure that the column has been assigned a full text index[/docs/{{version}}/migrations#available-index-types].
コレクションエンジンCollection Engine
「コレクション」エンジンは、迅速なプロトタイプ、非常に小さなデータセット(数百レコード程度)、またはテストの実行を目的としています。データベースから可能なすべてのレコードを取得し、PHPでLaravelのStr::isヘルパを使用してそれらをフィルタリングするため、インデックス作成やデータベース固有の機能は必要ありません。最小のユースケースを超えるものは、代わりにデータベースエンジンを使用する必要があります。The "collection" engine is intended for quick prototypes, extremely small datasets (a few hundred records), or running tests. It retrieves all possible records from your database and uses Laravel's Str::is helper to filter them in PHP, so it does not require any indexing or database-specific features. For anything beyond trivial use cases, you should use the database engine[#database-engine] instead.
コレクションエンジンを使用するには、SCOUT_DRIVER環境変数の値をcollectionに設定するか、アプリケーションのscout設定ファイルでcollectionドライバを直接指定してください。To use the collection engine, you may simply set the value of the SCOUT_DRIVER environment variable to collection, or specify the collection driver directly in your application's scout configuration file:
SCOUT_DRIVER=collection
使用するドライバとしてコレクションドライバを指定したら、モデルに対して検索クエリの実行を開始できます。Algolia、Meilisearch、Typesenseのインデックスにシードするために必要なインデックス作成などの検索エンジンインデックス作成は、コレクションエンジンを使用する場合には不要です。Once you have specified the collection driver as your preferred driver, you may start executing search queries[#searching] against your models. Search engine indexing, such as the indexing needed to seed Algolia, Meilisearch, or Typesense indexes, is unnecessary when using the collection engine.
データベースエンジンとの違いDifferences From Database Engine
データベースエンジンは、一致するレコードを効率的に見つけるために全文検索インデックスやLIKE句を使用しますが、コレクションエンジンはすべてのレコードを取得し、PHP内でそれらをフィルタリングします。コレクションエンジンは、Laravelがサポートするすべてのリレーショナルデータベース(SQLiteやSQL Serverを含む)で動作するため、最もポータブルな選択肢です。しかし、データベースエンジンよりも大幅に効率が劣るため、大規模なデータセットには使用しないでください。While the database engine uses full-text indexes and LIKE clauses to find matching records efficiently, the collection engine pulls all records and filters them in PHP. The collection engine is the most portable option as it works across all relational databases supported by Laravel (including SQLite and SQL Server); however, it is significantly less efficient than the database engine and should not be used with large datasets.
サードパーティエンジン設定Third-Party Engine Configuration
以下の設定オプションは、Algolia、Meilisearch、Typesenseなどのサードパーティ検索エンジンを使用する場合にのみ関連します。もしデータベースエンジンを使用している場合は、このセクションをスキップしてください。The following configuration options are only relevant when using a third-party search engine such as Algolia, Meilisearch, or Typesense. If you are using the database engine[#database-engine], you may skip this section.
モデルインデックスの設定Configuring Model Indexes
サードパーティエンジンを使用する場合、各Eloquentモデルは、そのモデルのすべてのSearchableレコードを含む指定検索「インデックス」と同期させます。デフォルトでは、各モデルはモデルの典型的な「テーブル」名と一致するインデックスに保存されます。通常、これはモデル名の複数形ですが、モデルのsearchableAsメソッドをオーバーライドすれば、モデルのインデックスを自由にカスタマイズできます。When using a third-party engine, each Eloquent model is synced with a given search "index", which contains all of the searchable records for that model. By default, each model will be persisted to an index matching the model's typical "table" name. Typically, this is the plural form of the model name; however, you are free to customize the model's index by overriding the searchableAs method on the model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Laravel\Scout\Searchable;
class Post extends Model
{
use Searchable;
/**
* モデルに関連付けているインデックスの名前を取得
*/
public function searchableAs(): string
{
return 'posts_index';
}
}
Note:
searchableAsメソッドは、常にモデルのデータベーステーブルを直接検索するデータベースエンジンを使用する場合には効果がありません。[!NOTE] ThesearchableAsmethod has no effect when using the database engine, which always searches the model's database table directly.
モデルIDの設定Configuring the Model ID
Scoutはデフォルトで、モデルの主キーを検索インデックスに保存するモデルの一意のID/キーとして使用します。サードパーティエンジンを使用する際に、この動作をカスタマイズする必要がある場合は、モデルのgetScoutKeyメソッドとgetScoutKeyNameメソッドをオーバーライドしてください。By default, Scout will use the primary key of the model as the model's unique ID / key that is stored in the search index. If you need to customize this behavior when using a third-party engine, you may override the getScoutKey and the getScoutKeyName methods on the model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Laravel\Scout\Searchable;
class User extends Model
{
use Searchable;
/**
* モデルをインデックスするために使用する値を取得
*/
public function getScoutKey(): mixed
{
return $this->email;
}
/**
* モデルをインデックスするために使用するキー名を取得
*/
public function getScoutKeyName(): mixed
{
return 'email';
}
}
Note:
getScoutKeyメソッドとgetScoutKeyNameメソッドは、常にモデルの主キーを使用するデータベースエンジンを使用する場合には効果がありません。[!NOTE] ThegetScoutKeyandgetScoutKeyNamemethods have no effect when using the database engine, which always uses the model's primary key.
AlgoliaAlgolia
インデックス設定Index Settings
Algoliaのインデックスへ設定を追加したい場合もあるでしょう。これらの設定はAlgoliaのUIから管理できますが、アプリケーションのconfig/scout.php設定ファイルで直接インデックス設定の望ましい状態を管理する方が効率的な場合もあります。Sometimes you may want to configure additional settings on your Algolia indexes. While you can manage these settings via the Algolia UI, it is sometimes more efficient to manage the desired state of your index configuration directly from your application's config/scout.php configuration file.
このアプローチにより、アプリケーションの自動デプロイパイプラインを通じて、これらの設定をデプロイできるようになります。手作業による設定を回避し、複数の環境間での一貫性を確保できます。フィルタリング可能な属性、ランキング、ファセット、もしくはサポート済みのその他の設定を設定可能です。This approach allows you to deploy these settings through your application's automated deployment pipeline, avoiding manual configuration and ensuring consistency across multiple environments. You may configure filterable attributes, ranking, faceting, or any other supported settings[https://www.algolia.com/doc/rest-api/search/#tag/Indices/operation/setSettings].
これを始めるには、アプリケーションのconfig/scout.php設定ファイルへ各インデックスの設定を追加します。To get started, add settings for each index in your application's config/scout.php configuration file:
use App\Models\User;
use App\Models\Flight;
'algolia' => [
'id' => env('ALGOLIA_APP_ID', ''),
'secret' => env('ALGOLIA_SECRET', ''),
'index-settings' => [
User::class => [
'searchableAttributes' => ['id', 'name', 'email'],
'attributesForFaceting'=> ['filterOnly(email)'],
// その他の設定項目…
],
Flight::class => [
'searchableAttributes'=> ['id', 'destination'],
],
],
],
指定するインデックスの元となるモデルが、ソフトデリート可能で、index-settings配列に含まれている場合、Scoutはそのインデックスのソフトデリート済みモデルに対するファセットを自動的にサポートします。ソフトデリート可能なモデルインデックスに対し定義するファセット属性が他にない場合は、そのモデルに対してindex-settings配列に空のエントリを追加するだけです。If the model underlying a given index is soft deletable and is included in the index-settings array, Scout will automatically include support for faceting on soft deleted models on that index. If you have no other faceting attributes to define for a soft deletable model index, you may simply add an empty entry to the index-settings array for that model:
'index-settings' => [
Flight::class => []
],
アプリケーションのインデックス設定を行った後は、scout:sync-index-settings Artisanコマンドを起動する必要があります。このコマンドは現在設定しているインデックス設定をAlgoliaへ通知します。このコマンドをデプロイプロセスの一部とすると便利でしょう。After configuring your application's index settings, you must invoke the scout:sync-index-settings Artisan command. This command will inform Algolia of your currently configured index settings. For convenience, you may wish to make this command part of your deployment process:
php artisan scout:sync-index-settings
ユーザーの識別Identifying Users
Scoutは、Algoliaを使用している場合、ユーザーを自動識別できます。認証済みユーザーを検索操作に関連付けることは、Algoliaのダッシュボード内で検索分析を表示する際に役立ちます。アプリケーションの.envファイルで、SCOUT_IDENTIFY環境変数をtrueとして定義することで、ユーザー識別を有効にできます。Scout allows you to auto identify users when using Algolia. Associating the authenticated user with search operations may be helpful when viewing your search analytics within Algolia's dashboard. You can enable user identification by defining a SCOUT_IDENTIFY environment variable as true in your application's .env file:
SCOUT_IDENTIFY=true
この機能を有効にすると、リクエストのIPアドレスと認証済みユーザーの主要な識別子もAlgoliaに渡されるため、このデータはユーザーが行うすべての検索リクエストに関連付けられます。Enabling this feature will also pass the request's IP address and your authenticated user's primary identifier to Algolia so this data is associated with any search request that is made by the user.
MeilisearchMeilisearch
インデックス設定Index Settings
Meilisearchでは、フィルタリング可能な属性、ソート可能な属性、およびその他のサポートされている設定フィールドなどのインデックス検索設定をあらかじめ定義しておく必要があります。Meilisearch requires you to pre-define index search settings such as filterable attributes, sortable attributes, and other supported settings fields[https://docs.meilisearch.com/reference/api/settings.html].
フィルタリング可能な属性とは、Scoutのwhereメソッドを呼び出す際にフィルタリングする予定の属性であり、ソート可能な属性とは、ScoutのorderByメソッドを呼び出す際にソートする予定の属性のことです。インデックスの設定を行うには、アプリケーションのscout設定ファイルにある、meilisearch設定項目のindex-settings部分を調整します。Filterable attributes are any attributes you plan to filter on when invoking Scout's where method, while sortable attributes are any attributes you plan to sort by when invoking Scout's orderBy method. To define your index settings, adjust the index-settings portion of your meilisearch configuration entry in your application's scout configuration file:
use App\Models\User;
use App\Models\Flight;
'meilisearch' => [
'host' => env('MEILISEARCH_HOST', 'http://localhost:7700'),
'key' => env('MEILISEARCH_KEY', null),
'index-settings' => [
User::class => [
'filterableAttributes'=> ['id', 'name', 'email'],
'sortableAttributes' => ['created_at'],
// その他の設定項目…
],
Flight::class => [
'filterableAttributes'=> ['id', 'destination'],
'sortableAttributes' => ['updated_at'],
],
],
],
インデックスの基盤となるモデルがソフトデリート可能で、かつindex-settings配列に含まれていれば、Scoutは自動的にそのインデックスのソフトデリートモデルに対するフィルタリングをサポートします。もし、ソフトデリート可能なモデルのインデックスに対して定義すべきフィルタリングやソート可能な属性がなければ、そのモデルに対し、index-settings配列へ空のエントリを追加するだけでよいでしょう。If the model underlying a given index is soft deletable and is included in the index-settings array, Scout will automatically include support for filtering on soft deleted models on that index. If you have no other filterable or sortable attributes to define for a soft deletable model index, you may simply add an empty entry to the index-settings array for that model:
'index-settings' => [
Flight::class => []
],
アプリケーションのインデックス設定後に、scout:sync-index-settings Artisanコマンドを呼び出す必要があります。このコマンドは、現在設定しているインデックス設定をMeilisearchに通知します。このコマンドをデプロイプロセスの一部とすると便利です。After configuring your application's index settings, you must invoke the scout:sync-index-settings Artisan command. This command will inform Meilisearch of your currently configured index settings. For convenience, you may wish to make this command part of your deployment process:
php artisan scout:sync-index-settings
SearchableデータタイプSearchable Data Types
Meilisearchは、正しい型のデータに対してのみフィルタ操作(>、<など)を実行します。Searchableデータをカスタマイズする際は、数値が正しい型にキャストされていることを確認してください。Meilisearch will only perform filter operations (>, <, etc.) on data of the correct type. When customizing your searchable data, you should ensure that numeric values are cast to their correct type:
public function toSearchableArray()
{
return [
'id' => (int) $this->id,
'name' => $this->name,
'price' => (float) $this->price,
];
}
TypesenseTypesense
Searchableデータの準備Preparing Searchable Data
Typesenseを使用する場合、Searchableモデルは、モデルの主キーを文字列に、作成日をUNIXタイムスタンプにキャストするtoSearchableArrayメソッドを定義する必要があります。When utilizing Typesense, your searchable models must define a toSearchableArray method that casts your model's primary key to a string and creation date to a UNIX timestamp:
/**
* モデルのインデックス可能なデータ配列の取得
*
* @return array<string, mixed>
*/
public function toSearchableArray(): array
{
return array_merge($this->toArray(),[
'id' => (string) $this->id,
'created_at' => $this->created_at->timestamp,
]);
}
また、アプリケーションのconfig/scout.phpファイルで、Typesenseコレクションスキーマを定義する必要もあります。コレクションスキーマは、Typesenseを介して検索可能な各フィールドのデータ型を記述します。利用可能なすべてのスキーマオプションの詳細については、Typesenseドキュメントを参照してください。You should also define your Typesense collection schemas in your application's config/scout.php file. A collection schema describes the data types of each field that is searchable via Typesense. For more information on all available schema options, please consult the Typesense documentation[https://typesense.org/docs/latest/api/collections.html#schema-parameters].
定義した後にTypesenseコレクションのスキーマを変更する必要がある場合は、scout:flushとscout:importを実行して既存のすべてのインデックス付きデータを削除し、スキーマを再作成できます。または、TypesenseのAPIを使用して、インデックス付きデータを削除せずにコレクションのスキーマを変更することもできます。If you need to change your Typesense collection's schema after it has been defined, you may either run scout:flush and scout:import, which will delete all existing indexed data and recreate the schema. Or, you may use Typesense's API to modify the collection's schema without removing any indexed data.
Searchableモデルがソフトデリート可能な場合は、アプリケーションのconfig/scout.php設定ファイル内のモデルに対応するTypesenseスキーマに__soft_deletedフィールドを定義する必要があります。If your searchable model is soft deletable, you should define a __soft_deleted field in the model's corresponding Typesense schema within your application's config/scout.php configuration file:
User::class => [
'collection-schema' => [
'fields' => [
// ...
[
'name' => '__soft_deleted',
'type' => 'int32',
'optional' => true,
],
],
],
],
動的検索パラメータDynamic Search Parameters
Typesenseでは、optionsメソッドを使用して検索操作を実行する際に、検索パラメータを動的に変更できます。Typesense allows you to modify your search parameters[https://typesense.org/docs/latest/api/search.html#search-parameters] dynamically when performing a search operation via the options method:
use App\Models\Todo;
Todo::search('Groceries')->options([
'query_by' => 'title, description'
])->get();
サードパーティエンジンインデックスThird-Party Engine Indexing
Note: このセクションで説明するインデックス機能は、主にサードパーティエンジン(Algolia、Meilisearch、またはTypesense)を使用する場合に関連します。データベースエンジンはデータベーステーブルを直接検索するため、手作業でのインデックス管理は不要です。[!NOTE] The indexing features described in this section are primarily relevant when using a third-party engine (Algolia, Meilisearch, or Typesense). The database engine searches your database tables directly, so it does not require manual index management.
バッチ取り込みBatch Import
Scoutを既存のプロジェクトにインストールする場合は、インデックスへインポートする必要のあるデータベースレコードがすでに存在している可能性があります。Scoutは、既存のすべてのレコードを検索インデックスにインポートするために使用できるscout:import Artisanコマンドを提供しています。If you are installing Scout into an existing project, you may already have database records you need to import into your indexes. Scout provides a scout:import Artisan command that you may use to import all of your existing records into your search indexes:
php artisan scout:import "App\Models\Post"
scout:queue-importコマンドはキュー投入ジョブを使用して既存レコードを全てインポートするために使用します。The scout:queue-import command may be used to import all of your existing records using queued jobs[/docs/{{version}}/queues]:
php artisan scout:queue-import "App\Models\Post" --chunk=500
flushコマンドは、検索インデックスからモデルの全レコードを削除するために使用します。The flush command may be used to remove all of a model's records from your search indexes:
php artisan scout:flush "App\Models\Post"
インポートクエリの変更Modifying the Import Query
バッチインポートで全モデルを取得するために使用されるクエリを変更する場合は、モデルにmakeAllSearchableUsingメソッドを定義してください。これはモデルをインポートする前に、必要になる可能性のあるイエガーリレーションの読み込みを追加するのに最適な場所です。If you would like to modify the query that is used to retrieve all of your models for batch importing, you may define a makeAllSearchableUsing method on your model. This is a great place to add any eager relationship loading that may be necessary before importing your models:
use Illuminate\Database\Eloquent\Builder;
/**
* 全モデルを検索可能にするときの、モデル取得に使用するクエリを変更
*/
protected function makeAllSearchableUsing(Builder $query): Builder
{
return $query->with('author');
}
Warning! キューを使用してモデルを一括インポートする場合、
makeAllSearchableUsingメソッドは適さないでしょう。モデルコレクションをジョブで処理する際に、リレーションが復元されないからです。[!WARNING] ThemakeAllSearchableUsingmethod may not be applicable when using a queue to batch import models. Relationships are not restored[/docs/{{version}}/queues#handling-relationships] when model collections are processed by jobs.
レコード追加Adding Records
モデルにLaravel\Scout\Searchableトレイトを追加したら、モデルインスタンスを保存または作成するだけで、検索インデックスに自動的に追加されます。キューを使用するようにScoutを設定した場合、この操作はキューワーカによってバックグラウンドで実行されます。Once you have added the Laravel\Scout\Searchable trait to a model, all you need to do is save or create a model instance and it will automatically be added to your search index. If you have configured Scout to use queues[#queueing] this operation will be performed in the background by your queue worker:
use App\Models\Order;
$order = new Order;
// ...
$order->save();
クエリによるレコード追加Adding Records via Query
Eloquentクエリを介してモデルのコレクションを検索インデックスに追加する場合は、searchableメソッドをEloquentクエリにチェーンできます。searchableメソッドはクエリの結果をチャンクし、レコードを検索インデックスに追加します。繰り返しますが、キューを使用するようにScoutを設定した場合、すべてのチャンクはキューワーカによってバックグラウンドでインポートされます。If you would like to add a collection of models to your search index via an Eloquent query, you may chain the searchable method onto the Eloquent query. The searchable method will chunk the results[/docs/{{version}}/eloquent#chunking-results] of the query and add the records to your search index. Again, if you have configured Scout to use queues, all of the chunks will be imported in the background by your queue workers:
use App\Models\Order;
Order::where('price', '>', 100)->searchable();
Eloquentリレーションインスタンスで searchableメソッドを呼び出すこともできます。You may also call the searchable method on an Eloquent relationship instance:
$user->orders()->searchable();
または、メモリ内にEloquentモデルのコレクションが既にある場合は、コレクションインスタンスでsearchableメソッドを呼び出して、モデルインスタンスを対応するインデックスに追加できます。Or, if you already have a collection of Eloquent models in memory, you may call the searchable method on the collection instance to add the model instances to their corresponding index:
$orders->searchable();
Note:
searchableメソッドは、「アップサート(upsert)」操作と考えるられます。つまり、モデルレコードがすでにインデックスに含まれている場合は、更新され、検索インデックスに存在しない場合は追加されます。[!NOTE] Thesearchablemethod can be considered an "upsert" operation. In other words, if the model record is already in your index, it will be updated. If it does not exist in the search index, it will be added to the index.
レコード更新Updating Records
検索可能モデルを更新するには、モデルインスタンスのプロパティを更新し、saveでモデルをデータベースへ保存します。Scoutは自動的に変更を検索インデックスへ保存します。To update a searchable model, you only need to update the model instance's properties and save the model to your database. Scout will automatically persist the changes to your search index:
use App\Models\Order;
$order = Order::find(1);
// 注文の更新処理…
$order->save();
Eloquentクエリインスタンスでsearchableメソッドを呼び出して、モデルのコレクションを更新することもできます。モデルが検索インデックスに存在しない場合は作成されます。You may also invoke the searchable method on an Eloquent query instance to update a collection of models. If the models do not exist in your search index, they will be created:
Order::where('price', '>', 100)->searchable();
リレーションシップ内のすべてのモデルの検索インデックスレコードを更新する場合は、リレーションシップインスタンスでsearchableを呼び出すことができます。If you would like to update the search index records for all of the models in a relationship, you may invoke the searchable on the relationship instance:
$user->orders()->searchable();
または、メモリ内にEloquentモデルのコレクションが既にある場合は、コレクションインスタンスでsearchableメソッドを呼び出して、対応するインデックスのモデルインスタンスを更新できます。Or, if you already have a collection of Eloquent models in memory, you may call the searchable method on the collection instance to update the model instances in their corresponding index:
$orders->searchable();
インポート前のレコードの変更Modifying Records Before Importing
時には検索可能にする前に、モデルのコレクションを準備する必要が起きる場合があります。例えば、関連するデータを効率よく検索インデックスに追加するため、リレーションをEagerロードしたいと思うでしょう。これを実現するには、対応するモデル上に、makeSearchableUsingメソッドを定義します:Sometimes you may need to prepare the collection of models before they are made searchable. For instance, you may want to eager load a relationship so that the relationship data can be efficiently added to your search index. To accomplish this, define a makeSearchableUsing method on the corresponding model:
use Illuminate\Database\Eloquent\Collection;
/**
* 検索可能なモデルのコレクションを変更する
*/
public function makeSearchableUsing(Collection $models): Collection
{
return $models->load('author');
}
検索インデックスの条件付き更新Conditionally Updating the Search Index
Scoutはデフォルトで、どの属性が変更されたかに関わらず、更新されたモデルを再インデックスします。この動作をカスタマイズしたい場合は、モデルにsearchIndexShouldBeUpdatedメソッドを定義してください。By default, Scout will reindex an updated model regardless of which attributes were modified. If you would like to customize this behavior, you may define a searchIndexShouldBeUpdated method on your model:
/**
* 検索インデックスを更新すべきか判断
*/
public function searchIndexShouldBeUpdated(): bool
{
return $this->wasRecentlyCreated || $this->wasChanged(['title', 'body']);
}
レコード削除Removing Records
インデックスからレコードを削除するには、データベースからモデルをdeleteするだけです。これは、ソフトデリートモデルを使用している場合でも実行できます。To remove a record from your index you may simply delete the model from the database. This may be done even if you are using soft deleted[/docs/{{version}}/eloquent#soft-deleting] models:
use App\Models\Order;
$order = Order::find(1);
$order->delete();
レコードを削除する前にモデルを取得したくない場合は、Eloquentクエリインスタンスでunsearchableメソッドを使用できます。If you do not want to retrieve the model before deleting the record, you may use the unsearchable method on an Eloquent query instance:
Order::where('price', '>', 100)->unsearchable();
リレーション内のすべてのモデルの検索インデックスレコードを削除する場合は、リレーションインスタンスでunsearchableを呼び出してください。If you would like to remove the search index records for all of the models in a relationship, you may invoke the unsearchable on the relationship instance:
$user->orders()->unsearchable();
または、メモリ内にEloquentモデルのコレクションが既にある場合は、コレクションインスタンスでunsearchableメソッドを呼び出して、対応するインデックスからモデルインスタンスを削除できます。Or, if you already have a collection of Eloquent models in memory, you may call the unsearchable method on the collection instance to remove the model instances from their corresponding index:
$orders->unsearchable();
すべてのモデルレコードを対応するインデックスから削除するには、removeAllFromSearchメソッドを呼び出します。To remove all of the model records from their corresponding index, you may invoke the removeAllFromSearch method:
Order::removeAllFromSearch();
インデックスの一時停止Pausing Indexing
モデルデータを検索インデックスに同期せずに、モデルに対してEloquent操作のバッチを実行する必要がある場合があります。これは、withoutSyncingToSearchメソッドを使用して行うことができます。このメソッドは、すぐに実行される単一のクロージャを引数に取ります。クロージャ内で発行するモデル操作は、モデルのインデックスに同期されません。Sometimes you may need to perform a batch of Eloquent operations on a model without syncing the model data to your search index. You may do this using the withoutSyncingToSearch method. This method accepts a single closure which will be immediately executed. Any model operations that occur within the closure will not be synced to the model's index:
use App\Models\Order;
Order::withoutSyncingToSearch(function () {
// モデルアクションを実行…
});
条件付き検索可能モデルインスタンスConditionally Searchable Model Instances
特定の条件下でのみ、モデルを検索可能にする必要がある場合も起きるでしょう。たとえば、App\Models\Postモデルが、"draft"か"published"の2つのうち、どちらか1つの状態を取ると想像してください。「公開済み:published」のポストのみ検索可能にする必要があります。これを実現するには、モデルにshouldBeSearchableメソッドを定義してください。Sometimes you may need to only make a model searchable under certain conditions. For example, imagine you have App\Models\Post model that may be in one of two states: "draft" and "published". You may only want to allow "published" posts to be searchable. To accomplish this, you may define a shouldBeSearchable method on your model:
/**
* モデルを検索可能にするかの判断
*/
public function shouldBeSearchable(): bool
{
return $this->isPublished();
}
shouldBeSearchableメソッドは、saveおよびcreateメソッド、クエリ、またはリレーションを通してモデルを操作する場合にのみ適用されます。searchableメソッドを使用してモデルまたはコレクションを直接検索可能にすると、shouldBeSearchableメソッドの結果が上書きされます。The shouldBeSearchable method is only applied when manipulating models through the save and create methods, queries, or relationships. Directly making models or collections searchable using the searchable method will override the result of the shouldBeSearchable method.
Warning! 検索可能なデータは常にデータベースへ保存されるため、
shouldBeSearchableメソッドはScoutの「データベース」エンジンを使用する際には適用されません。データベースエンジン使用時に同様の動作をさせるには、代わりにWHERE句を使用する必要があります。[!WARNING] TheshouldBeSearchablemethod is not applicable when using Scout's "database" engine, as all searchable data is always stored in the database. To achieve similar behavior when using the database engine, you should use where clauses[#where-clauses] instead.
検索Searching
searchメソッドにより、モデルの検索を開始しましょう。searchメソッドはモデルを検索するために使用する文字列だけを引数に指定します。getメソッドを検索クエリにチェーンし、指定した検索クエリに一致するEloquentモデルを取得できます。You may begin searching a model using the search method. The search method accepts a single string that will be used to search your models. You should then chain the get method onto the search query to retrieve the Eloquent models that match the given search query:
use App\Models\Order;
$orders = Order::search('Star Trek')->get();
Scoutの検索ではEloquentモデルのコレクションが返されるため、ルートやコントローラから直接結果を返せば、自動的にJSONへ変換されます。Since Scout searches return a collection of Eloquent models, you may even return the results directly from a route or controller and they will automatically be converted to JSON:
use App\Models\Order;
use Illuminate\Http\Request;
Route::get('/search', function (Request $request) {
return Order::search($request->search)->get();
});
Eloquentモデルへ変換する前に素の検索結果を取得したい場合は、rawメソッドを使用できます。If you would like to get the raw search results before they are converted to Eloquent models, you may use the raw method:
$orders = Order::search('Star Trek')->raw();
カスタムインデックスCustom Indexes
サードパーティエンジンを使用して検索する場合、検索クエリは通常、モデルのsearchableAsメソッドで指定するインデックスに対して実行されます。ただし、withinメソッドを使用して、代わりに検索する必要があるカスタムインデックスを指定できます。When searching using third-party engines, search queries will typically be performed on the index specified by the model's searchableAs[#configuring-model-indexes] method. However, you may use the within method to specify a custom index that should be searched instead:
$orders = Order::search('Star Trek')
->within('tv_shows_popularity_desc')
->get();
Where節Where Clauses
Scoutを使用すると、検索クエリに単純な「where」節を追加できます。現在、これらの節は基本的な同等性チェックのみをサポートしており、主に所有者IDによる検索クエリのスコープに役立ちます。Scout allows you to add simple "where" clauses to your search queries. Currently, these clauses only support basic equality checks and are primarily useful for scoping search queries by an owner ID:
use App\Models\Order;
$orders = Order::search('Star Trek')->where('user_id', 1)->get();
さらに、whereInメソッドを使うと、指定カラムの値が指定した配列内に含まれていることを確認できます。In addition, the whereIn method may be used to verify that a given column's value is contained within the given array:
$orders = Order::search('Star Trek')->whereIn(
'status', ['open', 'paid']
)->get();
whereNotInメソッドは、指定カラムの値が指定した配列に含まれないことを確認します。The whereNotIn method verifies that the given column's value is not contained in the given array:
$orders = Order::search('Star Trek')->whereNotIn(
'status', ['closed']
)->get();
Warning! アプリケーションでMeilisearchを使用している場合、Scoutの"where"句を利用する前に、アプリケーションのfilterable属性を設定する必要があります。[!WARNING] If your application is using Meilisearch, you must configure your application's filterable attributes[#meilisearch-index-settings] before utilizing Scout's "where" clauses.
Eloquent結果クエリのカスタマイズCustomizing the Eloquent Results Query
Scoutがアプリケーションの検索エンジンから一致するEloquentモデルのリストを取得した後、Eloquentを使用して主キーによりすべての一致するモデルを取得します。queryメソッドを呼び出すことで、このクエリをカスタマイズできます。queryメソッドは、Eloquentクエリビルダインスタンスを引数にするクロージャを引数に取ります。After Scout retrieves a list of matching Eloquent models from your application's search engine, Eloquent is used to retrieve all of the matching models by their primary keys. You may customize this query by invoking the query method. The query method accepts a closure that will receive the Eloquent query builder instance as an argument:
use App\Models\Order;
use Illuminate\Database\Eloquent\Builder;
$orders = Order::search('Star Trek')
->query(fn (Builder $query) => $query->with('invoices'))
->get();
サードパーティエンジンを使用する場合、このコールバックは関連するモデルが検索エンジンからすでに取得された後に呼び出されるため、結果の「フィルタリング」には使用しないでください。代わりにScoutのwhere句を使用してください。ただし、データベースエンジンを使用する場合、queryメソッドの制約はデータベースクエリに直接適用されるため、フィルタリングにも使用できます。When using a third-party engine, this callback is invoked after the relevant models have already been retrieved from the search engine, so it should not be used for "filtering" results — use Scout where clauses[#where-clauses] instead. However, when using the database engine, the query method's constraints are applied directly to the database query, so you may use it for filtering as well.
ペジネーションPagination
モデルのコレクションを取得することに加えて、paginateメソッドを使用して検索結果をページ分割することができます。このメソッドは、従来のEloquentクエリをペジネーションする場合と同じように、Illuminate\Pagination\LengthAwarePaginatorインスタンスを返します。In addition to retrieving a collection of models, you may paginate your search results using the paginate method. This method will return an Illuminate\Pagination\LengthAwarePaginator instance just as if you had paginated a traditional Eloquent query[/docs/{{version}}/pagination]:
use App\Models\Order;
$orders = Order::search('Star Trek')->paginate();
paginateメソッドの第1引数として、各ページごとに取得したいモデル数を指定します。You may specify how many models to retrieve per page by passing the amount as the first argument to the paginate method:
$orders = Order::search('Star Trek')->paginate(15);
データベースエンジンを使用する場合、simplePaginateメソッドも使用できます。ページ番号を表示するために一致するレコードの総数を取得するpaginateとは異なり、simplePaginateは現在のページ以降にさらに結果があるかどうかのみを判断します。これにより、「前へ」と「次へ」のリンクのみが必要な大規模なデータセットに対してより効率的になります。When using the database engine, you may also use the simplePaginate method. Unlike paginate, which retrieves the total number of matching records so it can display page numbers, simplePaginate only determines whether there are more results beyond the current page — making it more efficient for large datasets where you only need "previous" and "next" links:
$orders = Order::search('Star Trek')->simplePaginate(15);
結果が取得できたら、通常のEloquentクエリのペジネーションと同様に、結果を表示し、Bladeを使用してページリンクをレンダできます。Once you have retrieved the results, you may display the results and render the page links using Blade[/docs/{{version}}/blade] just as if you had paginated a traditional Eloquent query:
<div class="container">
@foreach ($orders as $order)
{{ $order->price }}
@endforeach
</div>
{{ $orders->links() }}
もちろん、ペジネーションの結果をJSONとして取得したい場合は、ルートまたはコントローラから直接ペジネータインスタンスを返すことができます。Of course, if you would like to retrieve the pagination results as JSON, you may return the paginator instance directly from a route or controller:
use App\Models\Order;
use Illuminate\Http\Request;
Route::get('/orders', function (Request $request) {
return Order::search($request->input('query'))->paginate(15);
});
Warning! 検索エンジンはEloquentモデルのグローバルスコープ定義を認識しないため、Scoutのペジネーションを利用するアプリケーションではグローバルスコープを使うべきでありません。それでも、Scoutにより検索する場合は、グローバルスコープの制約を再作成する必要があります。[!WARNING] Since search engines are not aware of your Eloquent model's global scope definitions, you should not utilize global scopes in applications that utilize Scout pagination. Or, you should recreate the global scope's constraints when searching via Scout.
ソフトデリートSoft Deleting
インデックス付きのモデルがソフトデリートされ、ソフトデリート済みのモデルをサーチする必要がある場合、config/scout.php設定ファイルのsoft_deleteオプションをtrueに設定してください。If your indexed models are soft deleting[/docs/{{version}}/eloquent#soft-deleting] and you need to search your soft deleted models, set the soft_delete option of the config/scout.php configuration file to true:
'soft_delete' => true,
この設定オプションをtrueにすると、Scoutは検索インデックスからソフトデリートされたモデルを削除しません。代わりに、インデックスされたレコードへ、隠し__soft_deleted属性をセットします。これにより、検索時にソフトデリート済みレコードを取得するために、withTrashedやonlyTrashedメソッドがつかえます。When this configuration option is true, Scout will not remove soft deleted models from the search index. Instead, it will set a hidden __soft_deleted attribute on the indexed record. Then, you may use the withTrashed or onlyTrashed methods to retrieve the soft deleted records when searching:
use App\Models\Order;
// 結果の取得時に、削除済みレコードも含める
$orders = Order::search('Star Trek')->withTrashed()->get();
// 結果の取得時に、削除済みレコードのみを対象とする
$orders = Order::search('Star Trek')->onlyTrashed()->get();
Note: ソフトデリートされたモデルが、
forceDeleteにより完全に削除されると、Scoutは自動的に検索インデックスから削除します。[!NOTE] When a soft deleted model is permanently deleted usingforceDelete, Scout will remove it from the search index automatically.
エンジンの検索のカスタマイズCustomizing Engine Searches
エンジンの検索動作の高度なカスタマイズを実行する必要がある場合は、 searchメソッドの2番目の引数にクロージャを渡せます。たとえば、このコールバックを使用して、検索クエリがAlgoliaに渡される前に、地理的位置データを検索オプションに追加できます。If you need to perform advanced customization of the search behavior of an engine you may pass a closure as the second argument to the search method. For example, you could use this callback to add geo-location data to your search options before the search query is passed to Algolia:
use Algolia\AlgoliaSearch\SearchIndex;
use App\Models\Order;
Order::search(
'Star Trek',
function (SearchIndex $algolia, string $query, array $options) {
$options['body']['query']['bool']['filter']['geo_distance'] = [
'distance' => '1000km',
'location' => ['lat' => 36, 'lon' => 111],
];
return $algolia->search($query, $options);
}
)->get();
カスタムエンジンCustom Engines
エンジンのプログラミングWriting the Engine
組み込みのScout検索エンジンがニーズに合わない場合、独自のカスタムエンジンを書き、Scoutへ登録してください。エンジンは、Laravel\Scout\Engines\Engine抽象クラスを拡張してください。この抽象クラスは、カスタムエンジンが実装する必要のある、8つのメソッドを持っています。If one of the built-in Scout search engines doesn't fit your needs, you may write your own custom engine and register it with Scout. Your engine should extend the Laravel\Scout\Engines\Engine abstract class. This abstract class contains eight methods your custom engine must implement:
use Laravel\Scout\Builder;
abstract public function update($models);
abstract public function delete($models);
abstract public function search(Builder $builder);
abstract public function paginate(Builder $builder, $perPage, $page);
abstract public function mapIds($results);
abstract public function map(Builder $builder, $results, $model);
abstract public function getTotalCount($results);
abstract public function flush($model);
これらのメソッドの実装をレビューするために、Laravel\Scout\Engines\AlgoliaEngineクラスが役に立つでしょう。このクラスは独自エンジンで、各メソッドをどのように実装すればよいかの、良い取り掛かりになるでしょう。You may find it helpful to review the implementations of these methods on the Laravel\Scout\Engines\AlgoliaEngine class. This class will provide you with a good starting point for learning how to implement each of these methods in your own engine.
エンジンの登録Registering the Engine
カスタムエンジンを作成したら、Scoutエンジンマネージャのextendメソッドを使用してScoutへ登録します。Scoutのエンジンマネージャは、Laravelサービスコンテナが依存解決できます。App\Providers\AppServiceProviderクラスのbootメソッドまたはアプリケーションが使用している他のサービスプロバイダからextendメソッドを呼び出せます。Once you have written your custom engine, you may register it with Scout using the extend method of the Scout engine manager. Scout's engine manager may be resolved from the Laravel service container. You should call the extend method from the boot method of your App\Providers\AppServiceProvider class or any other service provider used by your application:
use App\ScoutExtensions\MySqlSearchEngine;
use Laravel\Scout\EngineManager;
/**
* 全アプリケーションサービスの初期起動処理
*/
public function boot(): void
{
resolve(EngineManager::class)->extend('mysql', function () {
return new MySqlSearchEngine;
});
}
エンジンを登録したら、アプリケーションのconfig/scout.php設定ファイルでデフォルトのスカウトdriverとして指定できます。Once your engine has been registered, you may specify it as your default Scout driver in your application's config/scout.php configuration file:
'driver' => 'mysql',