Readouble

Laravel 5.8 Laravel Scout

イントロダクションIntroduction

Laravel Scout(スカウト、斥候)は、Eloquentモデルへ、シンプルなドライバベースのフルテキストサーチを提供します。モデルオブサーバを使い、Scoutは検索インデックスを自動的にEloquentレコードと同期します。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はAlgoliaドライバを用意しています。カスタムドライバは簡単に書けますので、独自の検索を実装し、Scoutを拡張できます。Currently, Scout ships with an Algolia[https://www.algolia.com/] driver; however, 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設定ファイルを公開します。このコマンドは、configディレクトリ下にscout.php設定ファイルを公開します。After installing Scout, you should publish the Scout configuration using the vendor:publish Artisan command. This command will publish the scout.php configuration file to your 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 to keep the model in sync with your search driver:

<?php

namespace App;

use Laravel\Scout\Searchable;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use Searchable;
}

キューQueueing

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,

ドライバの事前要件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:^2.2

設定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;

use Laravel\Scout\Searchable;
use Illuminate\Database\Eloquent\Model;

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;

use Laravel\Scout\Searchable;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use Searchable;

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

        // 配列のカスタマイズ…

        return $array;
    }
}

モデルIDの設定Configuring The Model ID

Scoutはデフォルトとして、モデルの主キーを検索インデックスへ保存するユニークなIDとして使用します。この振る舞いをカスタマイズしたい場合は、モデルのgetScoutKeyメソッドをオーバーライドしてください。By default, Scout will use the primary key of the model as the unique ID stored in the search index. If you need to customize this behavior, you may override the getScoutKey method on the model:

<?php

namespace App;

use Laravel\Scout\Searchable;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    use Searchable;

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

インデックスIndexing

バッチ取り込みBatch Import

既存プロジェクトに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 search driver. Scout provides an import Artisan command that you may use to import all of your existing records into your search indexes:

php artisan scout:import "App\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\Post"

レコード追加Adding Records

モデルにLaravel\Scout\Searchableトレイトを追加したら、必要なのはモデルインスタンスをsaveすることです。これにより自動的に検索インデックスへ追加されます。Scoutでキューを使用する設定にしている場合は、この操作はキューワーカにより、バックグランドで実行されます。Once you have added the Laravel\Scout\Searchable trait to a model, all you need to do is save 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:

$order = new App\Order;

// ...

$order->save();

クエリによる追加Adding Via Query

Eloquentクエリにより、検索インデックスへモデルのコレクションを追加したい場合は、Eloquentクエリにsearchableメソッドをチェーンします。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 an 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 added in the background by your queue workers:

// Eloquentクエリにより追加
App\Order::where('price', '>', 100)->searchable();

// リレーションにより、レコードを追加することもできる
$user->orders()->searchable();

// コレクションにより、追加することもできる
$orders->searchable();

searchableメソッドは"upsert(update insert)"操作と考えられます。言い換えれば、モデルレコードがインデックスへ既に存在していれば、更新されます。検索エンジンに存在していなければ、インデックスへ追加されます。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:

$order = App\Order::find(1);

// 注文を更新…

$order->save();

モデルのコレクションを更新するためにも、Eloquentクエリのsearchableメソッドを使用します。検索エンジンにモデルが存在していない場合は、作成します。You may also use the searchable method on an Eloquent query to update a collection of models. If the models do not exist in your search index, they will be created:

// Eloquentクエリによる更新
App\Order::where('price', '>', 100)->searchable();

// リレーションによる更新も可能
$user->orders()->searchable();

// コレクションによる更新も可能
$orders->searchable();

レコード削除Removing Records

インデックスからレコードを削除するには、データベースからモデルをdeleteで削除します。この形態による削除は、モデルのソフト削除と互換性があります。To remove a record from your index, delete the model from the database. This form of removal is even compatible with soft deleted[/docs/{{version}}/eloquent#soft-deleting] models:

$order = App\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 or collection:

// Eloquentクエリによる削除
App\Order::where('price', '>', 100)->unsearchable();

// リレーションによる削除も可能
$user->orders()->unsearchable();

// コレクションによる削除も可能
$orders->unsearchable();

インデックスの一時停止Pausing Indexing

Eloquentモデルをバッチ処理するが、検索インデックスへモデルデータを同期したくない場合も時々あります。withoutSyncingToSearchメソッドを使用することで可能です。このメソッドは、即時に実行されるコールバックを1つ引数に取ります。コールバック中のモデル操作は、インデックスへ同期されることはありません。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 callback which will be immediately executed. Any model operations that occur within the callback will not be synced to the model's index:

App\Order::withoutSyncingToSearch(function () {
    // モデルアクションの実行…
});

条件付き検索可能モデルインスタンスConditionally Searchable Model Instances

特定の条件下でのみ、モデルを検索可能にする必要がある場合も起きるでしょう。たとえば、App\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\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()
{
    return $this->isPublished();
}

shouldBeSearchableメソッドは、saveメソッド、クエリ、リレーションによるモデル操作の場合のみ適用されます。searchableメソッドを使用し、直接searchableなモデルかコレクションを作成する場合は、shouldBeSearchableメソッドの結果をオーバーライドします。The shouldBeSearchable method is only applied when manipulating models through the save method, queries, or relationships. Directly making models or collections searchable using the searchable method will override the result of the shouldBeSearchable method:

// "shouldBeSearchable"が利用される
App\Order::where('price', '>', 100)->searchable();

$user->orders()->searchable();

$order->save();

// "shouldBeSearchable"はオーバーライドされる
$orders->searchable();

$order->searchable();

検索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:

$orders = App\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 Illuminate\Http\Request;

Route::get('/search', function (Request $request) {
    return App\Order::search($request->search)->get();
});

Eloquentモデルにより変換される前の、結果をそのまま取得したい場合は、rawメソッドを使用してください。If you would like to get the raw results before they are converted to Eloquent models, you should use the raw method:

$orders = App\Order::search('Star Trek')->raw();

検索クエリは通常、モデルの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 = App\Order::search('Star Trek')
    ->within('tv_shows_popularity_desc')
    ->get();

Where節Where Clauses

Scoutは検索クエリに対して"WHERE"節を単に追加する方法も提供しています。現在、この節としてサポートしているのは、基本的な数値の一致を確認することだけで、主にIDにより検索クエリを絞り込むために使用します。検索インデックスはリレーショナル・データベースではないため、より上級の"WHERE"節は現在サポートしていません。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 a tenant ID. Since a search index is not a relational database, more advanced "where" clauses are not currently supported:

$orders = App\Order::search('Star Trek')->where('user_id', 1)->get();

ペジネーションPagination

コレクションの取得に付け加え、検索結果をpaginateメソッドでページづけできます。このメソッドは、Paginatorインスタンスを返しますので、Eloquentクエリのペジネーションと同様に取り扱えます。In addition to retrieving a collection of models, you may paginate your search results using the paginate method. This method will return a Paginator instance just as if you had paginated a traditional Eloquent query[/docs/{{version}}/pagination]:

$orders = App\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 = App\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() }}

ソフトデリート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:

// 結果の取得時に、削除済みレコードも含める
$orders = App\Order::search('Star Trek')->withTrashed()->get();

// 結果の取得時に、削除済みレコードのみを対象とする
$orders = App\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へサーチクエリが渡される前に、サーチオプションにgeo-locationデータを追加するために、このコールバックが利用できます。If you need to customize the search behavior of an engine you may pass a callback 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;

App\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($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へ登録します。AppServiceProviderかアプリケーションで使用している他のサービスプロバイダのbootメソッドで、extendメソッドを呼び出してください。たとえば、MySqlSearchEngineを書いた場合、次のように登録します。Once you have written your custom engine, you may register it with Scout using the extend method of the Scout engine manager. You should call the extend method from the boot method of your AppServiceProvider or any other service provider used by your application. For example, if you have written a MySqlSearchEngine, you may register it like so:

use Laravel\Scout\EngineManager;

/**
 * 全アプリケーションサービスの登録
 *
 * @return void
 */
public function boot()
{
    resolve(EngineManager::class)->extend('mysql', function () {
        return new MySqlSearchEngine;
    });
}

エンジンが登録できたら、Scoutのデフォルトdriverとして、config/scout.php設定ファイルで設定します。Once your engine has been registered, you may specify it as your default Scout driver in your config/scout.php configuration file:

'driver' => 'mysql',

ビルダマクロBuilder Macros

カスタムビルダメソッドを定義したい場合は、Laravel\Scout\Builderクラスのmacroメソッドを使用してください。通常、「マクロ」はサービスプロバイダbootメソッドの中で定義します。If you would like to define a custom 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:

<?php

namespace App\Providers;

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

class ScoutMacroServiceProvider extends ServiceProvider
{
    /**
     * アプリケーションのScoutマクロ登録
     *
     * @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 name as its first argument, and a Closure as its second. The macro's Closure will be executed when calling the macro name from a Laravel\Scout\Builder implementation:

App\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に保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作