Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Table of Contents

Note

laravel 5.3 에 도입된 scout 패키지를 사용하여 full text search engine 연계하는 방법

사전 준비


설치

  1. scout elastic search 패키지 설치

    Code Block
    languagebash
    titlelaravel 6.x
    $ composer require babenkoivan/scout-elasticsearch-driver
    Code Block
    languagebash
    titlelaravel 5.8
    $ composer require babenkoivan/scout-elasticsearch-driver "^3.0"
    Note

    3.12 버전은 Elastic 6.x 필요

  2. config/app.php 의 providers 에 아래 내용 추가 (No Package Discovery !) 

    Code Block
    'providers' => [
        Laravel\Scout\ScoutServiceProvider::class,
        ScoutElastic\ScoutElasticServiceProvider::class,
    ]
  3. config에 설정 파일을 생성하기 위해 vendor publish 수행

    Code Block
    php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"
    php artisan vendor:publish --provider="ScoutElastic\ScoutElasticServiceProvider"
  4. 컨피그 파일(config/scout_elastic.php) 설정
  5. .env 에 다음 내용을 추가하고 설정

    Code Block
    SCOUT_DRIVER=elasticsearch
    # This prefix may be useful if you have multiple| "tenants" or applications sharing the same search infrastructure.
    SCOUT_PREFIX=''
    ELASTICSEARCH_INDEX=laravel
    ##ELASTICSEARCH_HOST=localhost:9200
    
    ## laravel scout host
    SCOUT_ELASTIC_HOST=http://my-elastic.site:80
    Warning
    • nginx 를 붙여서 사용할 경우 SCOUT_ELASTIC_HOST 에 포트를 명시해야 함.(기본 9200)
    • URL 뒤에 trailing slash(Ex: my.site:80/) 를 붙이면 오작동하므로 주의!
  6. Queue 를 사용하여 인덱싱할 경우 config/scout.php 의 다음 항목을 true 로 설정

    Code Block
    'queue' => true,

Index configurator


Code Block
php artisan make:index-configurator MyIndexConfigurator
Code Block
languagephp
titleMyIndexConfigurator
<?php

namespace App;

use ScoutElastic\IndexConfigurator;
use ScoutElastic\Migratable;

class MyIndexConfigurator extends IndexConfigurator
{
    use Migratable;

    // It's not obligatory to determine name. By default it'll be a snaked class name without `IndexConfigurator` part.
    protected $name = 'my_index';

    // You can specify any settings you want, for example, analyzers.
    protected $settings = [
        'analysis' => [
            'analyzer' => [
                'kr_stdkorean' => [
                    'type' => 'standard',
                    'stopwords' => '_korean_'
                ]
            ]
        ]
    ];
}

...

Code Block
$ php artisan scout:import "App\User"


Record 추가

Laravel\Scout\Searchable 트레이트를 추가한 모델은  save() 메서드 호출시 자동으로 인덱싱

Code Block
$order = new App\Order;

// ...

$order->save();

...

See also