thaoha/eloquent-search

将 Eloquent 模型索引到 Elasticsearch

v1.0.3 2017-01-23 11:54 UTC

This package is not auto-updated.

Last update: 2024-09-28 20:25:23 UTC


README

Latest Stable Version License

将 Eloquent 模型索引到 Elasticsearch。Eloquent-search 使用 Elasticsearch 的官方低级客户端。您应该阅读有关 Elasticsearch 的更多信息,在 https://elastic.ac.cn 获取基本知识。

通过 Composer 安装

安装 eloquent-search 的推荐方法是使用 Composer

composer require thaoha/eloquent-search

一旦您运行了 composer update,您需要注册 Laravel 服务提供者,在您的 config/app.php

'providers' => [
    ...
    EloquentEs\EloquentEsServiceProvider::class,
],

或者使用 Lumen,您需要在 bootstrap/app.php 中添加

$app->register(EloquentEs\EloquentEsServiceProvider::class);

现在您可以将 ElasticModelTrait 添加到任何您想要索引到 Elasticsearch 的 Eloquent 模型中

use EloquentEs\Supports\ElasticModelTrait;

/**
 * Class Company
 * @package App\Models
 */
class Company extends Model
{
    use ElasticModelTrait;
    ...
}

配置

Laravel 5

$ php artisan vendor:publish --provider="EloquentEs\EloquentEsServiceProvider"

或者您可以将 config.php 文件复制到您的配置文件夹,并将文件名更改为 elastic.php。使用 Lumen 您需要在 bootstrap/app 中添加新的配置文件

$app->configure('elastic');

索引

首先创建索引以存储您的数据。使用模型类中的 esCreateIndex() 函数

App\Models\Company::esCreateIndex();

esCreateIndex() 函数使用 Company 模型中的属性 $esIndexMapping 来设置映射设置。如果 $esIndexMapping 为空,Elastic 将自动检测

/**
     * Index mapping
     *
     * @var array
     */
    private $esIndexMapping = [
        'id'            => ['type' => 'long'],
        'name'          => ['type' => 'string'],
        'company'       => ['type' => 'string']
    ];

如果您想更新映射设置,可以使用(在冲突错误时使用 esReset() 函数)

App\Models\Company::esPutMapping();

删除索引

App\Models\Company::esDeleteIndex();

重置索引。只需使用此函数(此函数将删除所有索引,包括您的数据,并使用映射设置创建新的一个)

App\Models\Company::esReset();

获取和索引模型

对于每个已经使用 ElasticModelTrait 的模型对象,您可以使用 esIndex() 函数将其索引到 Elasticsearch

$company = App\Models\Company::find(1);
$company->esIndex();

默认情况下,它将使用 $company->toArray() 获取数据。非常容易通过 esSerialize() 函数重写

/**
     * Get eloquent model data
     *
     * @return array
     */
    public function esSerialize()
    {
        $data = $this->toArray();
        $data['user_id'] = 1;
        
        return $data;
    }

删除模型

$company = App\Models\Company::find(1);
$company->esDelete();

更新模型

$company = App\Models\Company::find(1);
$company->esReindex();

您可以用相同的方式处理模型或集合。

搜索

$params = [
    'match' => ['name' => 'keyword']
];
$hits = App\Models\Company::esSearch($params);

您应该在 https://elastic.ac.cn/ 上阅读更多内容以构建您的搜索参数。