thomasjsn/laravel-scout-elastic

Elastic Driver for Laravel Scout

4.0.1 2017-08-02 07:21 UTC

This package is not auto-updated.

Last update: 2024-09-29 04:20:14 UTC


README

Software License Travis Packagist

此包为 Laravel Scout 提供了一个Elasticsearch 驱动。

内容

安装

您可以通过 composer 安装此包。

composer require thomasjsn/laravel-scout-elastic

您必须在 app.php 配置文件中添加 Scout 服务提供者和包服务提供者。

// config/app.php
'providers' => [
    ...
    Laravel\Scout\ScoutServiceProvider::class,
    ...
    ScoutEngines\Elasticsearch\ElasticsearchProvider::class,
],

然后,您应该使用 vendor:publish Artisan 命令发布 Elasticsearch 配置。

php artisan vendor:publish --provider="ScoutEngines\Elasticsearch\ElasticsearchProvider"

设置 Elasticsearch 配置

您必须有一个运行中的 Elasticsearch 服务器,可以使用 Artisan 命令创建索引;请参见以下内容。

发布 Laravel Scout 包配置后

// config/scout.php
// Set your driver to elasticsearch
    'driver' => env('SCOUT_DRIVER', 'elasticsearch'),

用法

使用适当的映射创建 Elasticsearch 索引

您可以在配置中定义 Elasticsearch 字段的自定义映射。请参阅配置文件中的示例。如果您更喜欢将映射存储在模型中,您可以在每个特定的模型中创建一个静态公共方法 mapping()

class Article extends Model
{
    // ...
    public static function mapping() {
        return [
            'location' => [
                'type' => 'geo_point'
            ],
        ];
    }
    // ...
}

然后在配置文件中使用它

 'indices' => [

    'realestate' => [
        'settings' => [
            "number_of_shards" => 1,
            "number_of_replicas" => 0,
        ],
        'mappings' => [
            'articles' => \App\Article::mapping(),
        ],
    ],
 ]

文档类型,在此示例中为 articles,必须与相应模型的 searchableAs() 匹配。

Elasticsearch 可以在第一次插入时为模型字段设置默认类型,如果您没有明确定义它们。然而,有时默认类型不是您想要的,或者您需要定义额外的映射属性。

在这种情况下,我们强烈建议在插入任何数据之前创建具有适当映射的索引。为此,有一个名为 elastic:make-indices {index} 的 Artisan 命令,它根据配置文件中的设置创建索引。

要创建配置中的所有索引,只需忽略 {index} 参数并运行

php artisan elastic:make-indices

如果索引存在,您将被询问是否要删除并重新创建它,或者您可以使用 --force 标志。

要获取有关现有 Elasticsearch 索引的信息,您可能想使用以下命令

php artisan elastic:indices

索引数据

您可以根据官方 Laravel Scout 文档中的说明索引您的数据。

搜索

该包支持 Laravel Scout 提供的所有内容。

Scout 的 search 方法使用配置文件中定义的默认查询方法。

使用 orderBy() 方法进行排序

$articles = Article::search($keywords)
            ->orderBy('id', 'desc')
            ->get();

Elastic 特定

然而,为了使用此包中包含的额外 Elasticsearch 功能,请通过将 ElasticSearchable 特性添加到您的模型中来代替 Searchable

class Article extends Model
{
    // use Searchable;
    use ElasticSearchable;
    // ...
}

包功能

  1. elasticSearch 方法,elasticSearch($method, $query, array $params = null)
$articles = Article::elasticSearch('multi_match', $q, [
    'fields' => ['title', 'content', 'tags'],
    'fuzziness' => 'auto',
    'prefix_length' => 2,
    'operator' => 'AND'
])->get();

参数从配置中获取,对于特定的查询方法,如果未提供,则使用。但您可以覆盖它们。

  1. 为每个模型创建单独的 Elasticsearch 索引。

如果您在配置文件中定义了多个索引,您可以通过在模型中重写 searchableWithin() 方法来选择模型所属的索引。

public function searchableWithin()
{
    return 'foobar';
}

如果您没有在您的模型中重写searchableWithin()方法,将使用配置中的第一个索引。

致谢

许可证

MIT许可(MIT)。