synergy/scout-elasticsearch-driver

Laravel Scout 的 Elasticsearch 驱动器

v2.1.0 2021-09-12 14:41 UTC

README

Latest Stable Version Total Downloads composer.lock Build Status Coverage Status

此包为在 Elasticsearch 中搜索和过滤数据提供高级功能。查看其功能

内容

功能

要求

此包已在以下配置中进行了测试

  • PHP 版本 >= 7.0
  • Laravel 框架版本 >= 5.5
  • Elasticsearch 版本 >= 5.5

安装

使用 composer 安装包

composer require synergy/scout-elasticsearch-driver

配置

要配置包,您需要首先发布设置

php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"
php artisan vendor:publish --provider="SynergyScoutElastic\providers\SynergyScoutElasticServiceProvider"

然后,在 config/scout.php 文件中将驱动设置设置为 elastic,并在 config/synergy-scout-elastic.php 文件中配置驱动本身。有两种可用选项

索引配置器

使用索引配置器类设置 Elasticsearch 索引的设置。要创建新的索引配置器,请使用以下 artisan 命令

php artisan make:index-configurator MyIndexConfigurator

它将在您项目的 app 文件夹中创建 MyIndexConfigurator.php 文件。您可以根据以下示例指定索引名称、设置和默认映射

<?php

namespace App;

use SynergyScoutElastic\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_'
                ]
            ]    
        ]
    ];

    // Common mapping for all types.
    protected $defaultMapping = [
        '_all' => [
            'enabled' => true
        ],
        'dynamic_templates' => [
            [
                'es' => [
                    'match' => '*_es',
                    'match_mapping_type' => 'string',
                    'mapping' => [
                        'type' => 'string',
                        'analyzer' => 'es_std'
                    ]
                ]    
            ]
        ]
    ];
}

有关索引设置和默认映射的更多信息,您可以在 Elasticsearch 文档的索引管理部分中找到。

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

php artisan elastic:create-index App\\MyIndexConfigurator

可搜索模型

要创建一个可以在 Elasticsearch 索引中执行搜索请求的模型,请使用以下命令

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

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

<?php

namespace App;

use SynergyScoutElastic\Models\Searchable;
use Illuminate\Database\Eloquent\Model;
use SynergyScoutElastic\Models\SearchableInterface;

class MyModel extends Model implements SearchableInterface
{
    use Searchable;

    protected $indexConfigurator = MyIndexConfigurator::class;

    protected $searchRules = [
        //
    ];

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

每个可搜索模型代表一个 Elasticsearch 类型。默认情况下,类型名称与表名称相同,但您可以通过 searchableAs 方法设置任何类型名称。您还可以通过 toSearchableArray 方法指定将索引由驱动程序索引的字段。有关这些选项的更多信息,您可以在 Scout 官方文档中找到。

MyModel 类中可以设置的最后一个重要选项是 $searchRules 属性。它允许您为模型设置不同的搜索算法。我们将在搜索规则部分中更详细地介绍它。

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

php artisan elastic:update-mapping App\\MyModel

使用方法

一旦创建了一个索引配置器、Elasticsearch 索引和可搜索模型,您就可以开始使用了。现在,您可以按照文档进行 索引搜索 数据。

除了标准功能外,该包还提供了一种在 Elasticsearch 中过滤数据而不指定查询字符串的可能性。

App\MyModel::search('*')
    ->where('id', 1)
    ->get();

此外,您可以覆盖模型的 搜索规则

App\MyModel::search('Brazil')
    ->rule(App\MySearchRule::class)
    ->get();

您还可以使用各种 where 条件。

App\MyModel::search('*')
    ->whereRegexp('name.raw', 'A.+')
    ->where('age', '>=', 30)
    ->whereExists('unemployed')
    ->get();

最后,如果您想发送自定义请求,可以使用 searchRaw 方法。

App\MyModel::searchRaw([
    'query' => [
        'bool' => [
            'must' => [
                'match' => [
                    '_all' => 'Brazil'
                ]
            ]
        ]
    ]
]);

此查询将返回原始响应。

控制台命令

以下列出了可用的 artisan 命令。

要获取详细说明和所有可用选项,请在命令行中运行 php artisan help [command]

搜索规则

搜索规则是一个类,用于描述搜索查询将如何执行。要创建搜索规则,请使用以下命令:

php artisan make:search-rule MySearchRule

在文件 app/MySearchRule.php 中,您将找到一个类定义。

<?php

namespace App;

use SynergyScoutElastic\SearchRule;

class MySearch extends SearchRule
{
    // This method returns an array that represents a content of bool query.
    public function buildQueryPayload()
    {
        return [
            'must' => [
                'match' => [
                    'name' => $this->builder->query
                ]
            ]
        ];
    }
}

您可以在 这里 了解更多关于 bool 查询的信息。

默认搜索规则返回以下负载。

return [
   'must' => [
       'match' => [
           '_all' => $this->builder->query
       ]
   ]
];

这意味着默认情况下,当您在模型上调用 search 方法时,它将尝试在任意字段中找到查询字符串。

要确定模型的默认搜索规则,只需添加一个属性即可。

<?php

namespace App;

use SynergyScoutElastic\Models\Searchable;
use Illuminate\Database\Eloquent\Model;
use SynergyScoutElastic\Models\SearchableInterface;

class MyModel extends Model implements SearchableInterface
{
    use Searchable;
    
    // You can set several rules for one model. In this case, the first not empty result will be returned.
    protected $searchRules = [
        MySearchRule::class
    ];
}

您还可以在查询构建器中设置搜索规则。

// You can set either a SearchRule class
App\MyModel::search('Brazil')
    ->rule(App\MySearchRule::class)
    ->get();
    
// or a callable
App\MyModel::search('Brazil')
    ->rule(function($builder) {
        return [
            'must' => [
                'match' => [
                    'Country' => $builder->query
                ]
            ]
        ];
    })
    ->get();

可用过滤器

您可以使用不同类型的过滤器。

在大多数情况下,最好使用原始字段来过滤记录,即非分析字段。

调试

有两种方法可以帮助您分析搜索查询的结果。

  • explain

    App\MyModel::search('Brazil')
        ->first()
        ->explain();
  • profile

    App\MyModel::search('Brazil')
        ->first()
        ->profile();

这两种方法都返回来自 ES 的原始数据。

此外,您可以通过调用 buildPayload 方法获取将发送到 ES 的查询负载。

App\MyModel::search('Brazil')
    ->buildPayload();

请注意,此方法返回一个负载集合,因为可能在一个查询中使用多个搜索规则。