amitavroy / laravel-elastic
一个包,能够使数据在Elasticsearch上索引,并允许对单个模型进行搜索。
v1.1.1
2018-10-25 02:49 UTC
Requires
- elasticsearch/elasticsearch: ^6.0.0
- laravel/framework: ~5.5.0|~5.6.0|~5.7.0
This package is auto-updated.
Last update: 2024-09-13 13:17:18 UTC
README
此包允许您轻松地使用Elasticsearch与Eloquent模型一起使用。此包将为您的应用程序中的每个模型创建单独的索引,并使用Eloquent事件'created'、'updated'和'deleted',此包将保持您的Elastic索引同步。
安装和使用
此包与Elasticsearch 6.0及以上版本最佳兼容。
要安装,您只需使用以下命令要求该包
composer require amitavroy/laravel-elastic
设置和配置
此包附带一个配置文件,您需要将其发布并设置主机数组。这是包如何访问Elasticsearch实例的方式。
'hosts' => [
'https://:6200',
],
此外,如果您使用同一个Elasticsearch实例为多个应用程序,您还可以为索引定义一个前缀。
'prefix' => 'some_prefix_',
使用方法
此包提供了一个特质,您需要将其添加到任何希望被索引和搜索的Eloquent模型中。您还需要指定您想要在该模型上搜索哪些字段。例如,您不希望存储和搜索用户的密码、记住令牌或某些其他敏感数据。
<?php
namespace App;
use Amitav\LaravelElastic\Traits\Searchable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Searchable;
protected $searchFields = [
'name', 'address', 'phone'
];
}
使用此配置,如果创建了新用户,内容将得到索引。对于更新和删除也是如此。
使用具有Searchable特质的任何模型可用的某些附加方法包括
User::reindex();
这将清除当前创建的Elasticsearch索引并重新索引整个内容。
最重要的方法是搜索。在任何使用Searchable特质的Eloquent模型上,您都可以执行以下操作
User::search('keyword');
这将返回包含如命中次数、执行时间、得分和搜索结果等数据点的Elasticsearch响应。还有一个选项,您可以通过传递第二个参数为true来获取结果作为集合。
User::search('keyword', true);