laravel5.7 使用 Elasticsearch 做引擎,scout 全文搜索

  • 准备工作
    通过 Composer 包管理器来安装 Scout
    composer require laravel/scout

通过 Composer 包管理器来安装 scout-elasticsearch-driver

composer require babenkoivan/scout-elasticsearch-driver
  • 基本配置
    Scout,安装完成后,使用 vendor:publish Artisan 命令来生成 Scout 配置文件。这个命令将在你的 config 目录下生成一个 scout.php 配置文件。
php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"
php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"

php artisan vendor:publish --provider="ScoutElasticScoutElasticServiceProvider"

  • 索引配置
    索引配置程序类用于设置Elasticsearch索引的设置。要创建新的索引配置程序,请使用以下artisan命令:
<?php
namespace App;
use ScoutElastic\IndexConfigurator;

class MyIndexConfigurator extends IndexConfigurator

{
// 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' => [
            'es_std' => [
                'type' => 'standard',
                'stopwords' => '_spanish_'
            ]
        ]    
    ]
];
}

它将MyIndexConfigurator.php在app项目的文件夹中创建文件。您可以指定索引名称和设置,如以下示例所示:

<?php
namespace App;
use ScoutElastic\IndexConfigurator;
class MyIndexConfigurator extends IndexConfigurator
{
// 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' => [
            'es_std' => [
                'type' => 'standard',
                'stopwords' => '_spanish_'
            ]
        ]    
    ]
];
}

要创建索引,只需运行artisan命令:

php artisan elastic:create-index App\\MyIndexConfigurator
  • 可搜索的模型

要创建能够在Elasticsearch索引中执行搜索请求的模型,请使用以下命令:

php artisan make:searchable-model MyModel --index-configurator=MyIndexConfigurator

执行命令后,您将MyModel.php在您的app文件夹中找到该文件:

<?php
namespace App;
use ScoutElastic\Searchable;
use Illuminate\Database\Eloquent\Model;
class MyModel extends Model
{
use Searchable;

protected $indexConfigurator = MyIndexConfigurator::class;

protected $searchRules = [
    //
];

// Here you can specify a mapping for a model fields.
protected $mapping = [
    'properties' => [
        'text' => [
            'type' => 'text',
            'fields' => [
                'raw' => [
                    'type' => 'keyword',
                ]
            ]
        ],
    ]
];
}

在模型中设置映射后,您可以更新Elasticsearch类型映射:

php artisan elastic:update-mapping App\\MyModel
  • 映射数据到索引
php artisan scout:import App\\MyModel

本文链接:

http://xueyuphp.cn/index.php/archives/32/
1 + 8 =
0 评论