wppd / scout-elasticsearch-driver

Laravel Scout 的 Elasticsearch 驱动程序

该软件包的规范存储库似乎已消失,因此该软件包已被冻结。

v4.0.4 2020-03-17 20:17 UTC

README

Packagist Packagist Build Status Donate

🍺 如果你喜欢我的包,你可以通过 购买我一杯啤酒

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

内容

功能

  • 一种简单的方式来 配置创建 一个 Elasticsearch 索引。
  • 为每个 模型 提供完全可配置的映射。
  • 可以将新字段自动添加到现有映射中 使用 Artisan 命令
  • 多种不同的方法来实现您的搜索算法:使用 搜索规则 或原始搜索。
  • 提供各种 过滤类型 以使搜索查询更加具体。
  • 从旧索引到新索引的 零停机迁移
  • 批量索引,请参阅 配置部分

要求

该软件包已在以下配置中进行过测试

  • PHP 版本 >=7.1.3, <=7.3
  • Laravel 框架版本 >=5.8, <=6
  • Elasticsearch 版本 >=7

安装

使用 composer 安装软件包

composer require babenkoivan/scout-elasticsearch-driver

如果您正在使用 Laravel 版本 <= 5.4 或禁用了 软件包发现,请在 config/app.php 中添加以下提供者

'providers' => [
    Laravel\Scout\ScoutServiceProvider::class,
    ScoutElastic\ScoutElasticServiceProvider::class,
]

配置

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

php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"
php artisan vendor:publish --provider="ScoutElastic\ScoutElasticServiceProvider"

然后,在 config/scout.php 文件中将驱动设置设置为 elastic 并在 config/scout_elastic.php 文件中配置驱动本身。可用的选项包括

选项 描述
client 用于构建 Elasticsearch 客户端的设置哈希。更多信息请参阅 此处。默认主机设置为 localhost:9200
update_mapping 指定是否自动更新映射的选项。默认设置为 true
indexer 将此选项设置为single以进行单个文档索引,或设置为bulk以进行批量文档索引。默认设置为single
document_refresh 此选项控制更新后的文档何时出现在搜索结果中。可以设置为'true''false''wait_for'null。有关此选项的更多详细信息,请参阅此处。默认设置为null

注意,如果您使用批量文档索引,您可能希望更改块大小,您可以在config/scout.php文件中这样做。

索引配置器

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

php artisan make:index-configurator MyIndexConfigurator

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

<?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_'
                ]
            ]    
        ]
    ];
}

有关索引设置的更多信息,请参阅Elasticsearch文档中的索引管理部分

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

php artisan elastic:create-index "App\MyIndexConfigurator"

请注意,每个可搜索模型都需要其自己的索引配置器。

在Elasticsearch 6.0.0或更高版本中创建的索引可能只能包含单个映射类型。在5.x版本中创建的具有多个映射类型的索引将继续在Elasticsearch 6.x中按原样工作。在Elasticsearch 7.0.0中,映射类型将被完全删除。

有关更多信息,请参阅此处

可搜索模型

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

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

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

<?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 model fields
    protected $mapping = [
        'properties' => [
            'title' => [
                'type' => 'text',
                // Also you can configure multi-fields, more details you can find here https://elastic.ac.cn/guide/en/elasticsearch/reference/current/multi-fields.html
                'fields' => [
                    'raw' => [
                        'type' => 'keyword',
                    ]
                ]
            ],
        ]
    ];
}

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

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

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

php artisan elastic:update-mapping "App\MyModel"

用法

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

基本搜索用法示例

// set query string
App\MyModel::search('phone')
    // specify columns to select
    ->select(['title', 'price'])
    // filter 
    ->where('color', 'red')
    // sort
    ->orderBy('price', 'asc')
    // collapse by field
    ->collapse('brand')
    // set offset
    ->from(0)
    // set limit
    ->take(10)
    // get results
    ->get();

如果您只需要查询的匹配项数量,请使用count方法

App\MyModel::search('phone') 
    ->count();

如果您需要加载关系,请使用with方法

App\MyModel::search('phone') 
    ->with('makers')
    ->get();

除了标准功能外,此包还为您提供了一种无需指定查询字符串即可在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 命令

命令 参数 描述
make:index-configurator name - 类的名称 创建一个新的 Elasticsearch 索引配置器。
make:searchable-model name - 类的名称 创建一个新的可搜索模型。
make:search-rule name - 类的名称 创建一个新的搜索规则。
elastic:create-index index-configurator - 索引配置器类 创建一个 Elasticsearch 索引。
elastic:update-index index-configurator - 索引配置器类 更新 Elasticsearch 索引的设置和映射。
elastic:drop-index index-configurator - 索引配置器类 删除 Elasticsearch 索引。
elastic:update-mapping model - 模型类 更新模型映射。
elastic:migrate model - 模型类,target-index - 要迁移的索引名称 将模型迁移到另一个索引。

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

搜索规则

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

php artisan make:search-rule MySearchRule

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

<?php

namespace App;

use ScoutElastic\SearchRule;

class MySearch extends SearchRule
{
    // This method returns an array, describes how to highlight the results.
    // If null is returned, no highlighting will be used. 
    public function buildHighlightPayload()
    {
        return [
            'fields' => [
                'name' => [
                    'type' => 'plain'
                ]
            ]
        ];
    }
    
    // This method returns an array, that represents bool query.
    public function buildQueryPayload()
    {
        return [
            'must' => [
                'match' => [
                    'name' => $this->builder->query
                ]
            ]
        ];
    }
}

您可以在 这里 阅读有关 bool 查询的更多信息,以及在 这里 阅读有关高亮显示的更多信息。

默认搜索规则返回以下有效载荷

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

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

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

<?php

namespace App;

use ScoutElastic\Searchable;
use Illuminate\Database\Eloquent\Model;

class MyModel extends Model
{
    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();

要获取高亮显示,请使用模型的 highlight 属性

// Let's say we highlight field `name` of `MyModel`.
$model = App\MyModel::search('Brazil')
    ->rule(App\MySearchRule::class)
    ->first();

// Now you can get raw highlighted value:
$model->highlight->name;

// or string value:
 $model->highlight->nameAsString;

可用过滤器

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

方法 示例 描述
where($field, $value) where('id', 1) 检查与简单值的相等性。
where($field, $operator, $value) where('id', '>=', 1) 根据给定的规则过滤记录。可用的运算符有:=, <, >, <=, >=, <>。
whereIn($field, $value) where('id', [1, 2, 3]) 检查一个值是否在值集中。
whereNotIn($field, $value) whereNotIn('id', [1, 2, 3]) 检查一个值是否不在值集中。
whereBetween($field, $value) whereBetween('price', [100, 200]) 检查一个值是否在范围内。
whereNotBetween($field, $value) whereNotBetween('price', [100, 200]) 检查一个值是否不在范围内。
whereExists($field) whereExists('unemployed') 检查一个值是否已定义。
whereNotExists($field) whereNotExists('unemployed') 检查一个值是否未定义。
whereRegexp($field, $value, $flags = 'ALL') whereRegexp('name.raw', 'A.+') 根据给定的正则表达式过滤记录。有关语法的更多信息,请参阅 这里
whereGeoDistance($field, $value, $distance) whereGeoDistance('location', [-70, 40], '1000m') 根据给定的点和它之间的距离过滤记录。有关语法的更多信息,请参阅 这里
whereGeoBoundingBox($field, array $value) whereGeoBoundingBox('location', ['top_left' => [-74.1, 40.73], 'bottom_right' => [-71.12, 40.01]]) 在给定范围内过滤记录。有关语法更多信息,请点击这里
whereGeoPolygon($field, array $points) whereGeoPolygon('location', [[-70, 40],[-80, 30],[-90, 20]]) 在给定多边形内过滤记录。有关语法更多信息,请点击这里
whereGeoShape($field, array $shape, $relation = 'INTERSECTS') whereGeoShape('shape', ['type' => 'circle', 'radius' => '1km', 'coordinates' => [4, 52]], 'WITHIN') 在给定形状内过滤记录。有关语法更多信息,请点击这里

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

零停机迁移

如您所知,您无法更改Elasticsearch中已创建的字段类型。在这种情况下,唯一的选择是创建一个新的索引,包含必要的映射,并将模型导入到新索引中。
迁移可能需要相当长的时间,因此为了在过程中避免停机,驱动程序从旧索引读取并写入新索引。迁移完成后,它开始从新索引读取并删除旧索引。这就是 artisan elastic:migrate 命令的工作方式。

在运行该命令之前,请确保您的索引配置器使用 ScoutElastic\Migratable trait。如果不是,请添加该trait,并使用索引配置器类名作为参数运行 artisan elastic:update-index 命令。

php artisan elastic:update-index "App\MyIndexConfigurator"

准备好后,在模型映射中做出更改,并使用模型类作为第一个参数,使用所需索引名称作为第二个参数运行 elastic:migrate 命令。

php artisan elastic:migrate "App\MyModel" my_index_v2

注意,如果您只想在映射中添加新字段,请使用 elastic:update-mapping 命令。

调试

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

  • explain

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

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

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

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

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

请注意,由于一个查询中可能使用多个搜索规则,该方法返回有效负载的集合。