Readouble

Laravel 8.x Laravel Scout

イントロダクション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.

現在、ScoutはAlgoliaMeiliSearchドライバを用意しています。さらに、Scoutは、ローカル開発用に設計した"collection"ドライバも用意しており、これは外部依存やサードパーティのサービスを必要としません。さらに、カスタムドライバの記述も簡単で、独自な検索実装を行い自由にScoutを拡張できます。Currently, Scout ships with Algolia[https://www.algolia.com/] and MeiliSearch[https://www.meilisearch.com] drivers. In addition, Scout includes a "collection" driver that is designed for local development usage and does not require any external dependencies or third-party services. Furthermore, writing custom drivers is simple and you are free to extend Scout with your own search implementations.

インストール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;
}

ドライバの事前要件Driver Prerequisites

AlgoliaAlgolia

Algoliaドライバを使用する場合、Algolia idsecret接続情報を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 blazingly fast and 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環境変数とMeiliSearchhostkey認証情報を設定します。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].

Note: note MeiliSearchを利用しているアプリケーションのScoutをアップグレードする際には、常にMeiliSearchサービス自体に追加の破壊的な変更がないか確認する必要があります。{note} 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.

キュー投入Queueing

厳密にはScoutを使用する必要はありませんが、ライブラリを使用する前に、キュードライバの設定を強く考慮する必要があります。キューワーカを実行すると、Scoutはモデル情報を検索インデックスに同期するすべての操作をキューに入れることができ、アプリケーションのWebインターフェイスのレスポンス時間が大幅に短縮されます。While not strictly required to use Scout, 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,

設定Configuration

モデルインデックスの設定Configuring Model Indexes

各Eloquentモデルは、検索可能レコードすべてを含む、指定された検索「インデックス」と同期されます。言い換えれば、各インデックスはMySQLテーブルのようなものであると、考えられます。デフォルトで、各モデルはそのモデルの典型的な「テーブル」名に一致するインデックスへ保存されます。通常、モデルの複数形ですが、モデルのsearchableAsメソッドをオーバーライドすることで、このモデルのインデックスを自由にカスタマイズ可能です。Each Eloquent model is synced with a given search "index", which contains all of the searchable records for that model. In other words, you can think of each index like a MySQL table. 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;

    /**
     * モデルに関連付けられているインデックスの名前を取得
     *
     * @return string
     */
    public function searchableAs()
    {
        return 'posts_index';
    }
}

検索可能データの設定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;

    /**
     * モデルのインデックス可能なデータ配列の取得
     *
     * @return array
     */
    public function toSearchableArray()
    {
        $array = $this->toArray();

        // データ配列をカスタマイズ

        return $array;
    }
}

モデルIDの設定Configuring The Model ID

デフォルトでは、Scoutはモデルの主キーを、検索インデックスに保存されているモデルの一意のID/キーとして使用します。この動作をカスタマイズする必要がある場合は、モデルのgetScoutKeyメソッドとgetScoutKeyNameメソッドをオーバーライドできます。By default, Scout will use the primary key of the model as model's unique ID / key that is stored in the search index. If you need to customize this behavior, 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;

    /**
     * モデルのインデックスに使用する値の取得
     *
     * @return mixed
     */
    public function getScoutKey()
    {
        return $this->email;
    }

    /**
     * モデルのインデックスに使用するキー名の取得
     *
     * @return mixed
     */
    public function getScoutKeyName()
    {
        return 'email';
    }
}

ユーザーの識別Identifying Users

Scoutを使用すると、Algoliaを使用するときにユーザーを自動識別することもできます。認証済みユーザーを検索操作に関連付けると、Algoliaのダッシュボード内で検索分析を表示するときに役立つ場合があります。アプリケーションの.envファイルでSCOUT_IDENTIFY環境変数をtrueとして定義することにより、ユーザー識別を有効にできます。Scout also allows you to auto identify users when using Algolia[https://algolia.com]. 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 this 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.

ローカル開発Local Development

ローカル開発時には、AlgoliaやMeiliSearchの検索エンジンを自由に使用することができますが、「コレクション(collection)」エンジンでスタートした方が便利な場合もあります。コレクション・エンジンは、既存データベースからの結果に対して、「where」節とコレクション・フィルタリングを用いて、クエリに該当する検索結果を決定します。このエンジンを使用する場合、Searchableモデルをインデックス化する必要はなく、シンプルにローカル・データベースから検索します。While you are free to use the Algolia or MeiliSearch search engines during local development, you may find it more convenient to get started with the "collection" engine. The collection engine will use "where" clauses and collection filtering on results from your existing database to determine the applicable search results for your query. When using this engine, it is not necessary to "index" your searchable models, as they will simply be retrieved from your local database.

コレクションエンジンを使用するには,環境変数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のインデックスのシードに必要なインデックス作成などの検索エンジンのインデックス作成は不要です。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 or MeiliSearch indexes, is unnecessary when using the collection engine.

インデックスIndexing

バッチ取り込み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"

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:

/**
 * 全モデルを検索可能にするときの、モデル取得に使用するクエリを変更
 *
 * @param  \Illuminate\Database\Eloquent\Builder  $query
 * @return \Illuminate\Database\Eloquent\Builder
 */
protected function makeAllSearchableUsing($query)
{
    return $query->with('author');
}

レコード追加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();

lightbulb">Tip!! searchableメソッドは、「アップサート(upsert)」操作と考えるられます。つまり、モデルレコードがすでにインデックスに含まれている場合は、更新され、検索インデックスに存在しない場合は追加されます。{tip} The searchable method 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();

レコード削除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();

インデックスの一時停止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:

/**
 * モデルを検索可能にする判定
 *
 * @return bool
 */
public function shouldBeSearchable()
{
    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.

検索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メソッドを使用して、代わりに検索する必要があるカスタムインデックスを指定できます。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 numeric 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メソッドを使用すると、指定された値の集合に対して結果を制約できます。You may use the whereIn method to constrain results against a given set of values:

$orders = Order::search('Star Trek')->whereIn(
    'status', ['paid', 'open']
)->get();

検索インデックスはリレーショナルデータベースではないため、より高度な"where"節は現在サポートしていません。Since a search index is not a relational database, more advanced "where" clauses are not currently supported.

ペジネーション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);

結果が取得できたら、通常の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);
});

ソフトデリート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属性をセットします。これにより、検索時にソフトデリート済みレコードを取得するために、withTrashedonlyTrashedメソッドがつかえます。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();

lightbulb">Tip!! ソフトデリートされたモデルが、forceDeleteにより完全に削除されると、Scoutは自動的に検索インデックスから削除します。{tip} When a soft deleted model is permanently deleted using forceDelete, 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;

/**
 * 全アプリケーションサービスの初期起動処理
 *
 * @return void
 */
public function boot()
{
    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',

ビルダマクロBuilder Macros

カスタムのScout検索ビルダメソッドを定義する場合は、Laravel\Scout\Builderクラスでmacroメソッドが使用できます。通常、「マクロ」はサービスプロバイダbootメソッド内で定義する必要があります。If you would like to define a custom Scout search builder method, you may use the macro method on the Laravel\Scout\Builder class. Typically, "macros" should be defined within a service provider's[/docs/{{version}}/providers] boot method:

use Illuminate\Support\Facades\Response;
use Illuminate\Support\ServiceProvider;
use Laravel\Scout\Builder;

/**
 * 全アプリケーションサービスの初期起動処理
 *
 * @return void
 */
public function boot()
{
    Builder::macro('count', function () {
        return $this->engine->getTotalCount(
            $this->engine()->search($this)
        );
    });
}

macro関数は、最初の引数にマクロ名、2番目の引数にクロージャを取ります。マクロのクロージャは、Laravel\Scout\Builder実装からマクロ名を呼び出すときに実行されます。The macro function accepts a macro name as its first argument and a closure as its second argument. The macro's closure will be executed when calling the macro name from a Laravel\Scout\Builder implementation:

use App\Models\Order;

Order::search('Star Trek')->count();

章選択

設定

明暗テーマ
light_mode
dark_mode
brightness_auto システム設定に合わせる
テーマ選択
photo_size_select_actual デフォルト
photo_size_select_actual モノクローム(白黒)
photo_size_select_actual Solarized風
photo_size_select_actual GitHub風(青ベース)
photo_size_select_actual Viva(黄緑ベース)
photo_size_select_actual Happy(紫ベース)
photo_size_select_actual Mint(緑ベース)
コードハイライトテーマ選択

明暗テーマごとに、コードハイライトのテーマを指定できます。

テーマ配色確認
スクリーン表示幅
640px
80%
90%
100%

768px以上の幅があるときのドキュメント部分表示幅です。

インデント
無し
1rem
2rem
3rem
原文確認
原文を全行表示
原文を一行ずつ表示
使用しない

※ 段落末のEボタンへカーソルオンで原文をPopupします。

Diff表示形式
色分けのみで区別
行頭の±で区別
削除線と追記で区別

※ [tl!…]形式の挿入削除行の表示形式です。

Pagination和文
ペジネーション
ペギネーション
ページネーション
ページ付け
Scaffold和文
スカフォールド
スキャフォールド
型枠生成
本文フォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

コードフォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

保存内容リセット

localStrageに保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作