在 laravel 中使用 elaticsearch
安装相关扩展包
- babenkoivan/scout-elasticsearch-driver
- predis/predis 数据量大需要使用队列同步、拉取数据时安装
安装 scout 第三方驱动 babenkoivan/scout-elasticsearch-driver
composer require babenkoivan/scout-elasticsearch-driver
发布配置文件
php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"
php artisan vendor:publish --provider="ScoutElastic\ScoutElasticServiceProvider"
scout 服务配置,在 env 中增加配置项
# 驱动的host,若需账密:http://es_username:password@127.0.0.1:9200
SCOUT_ELASTIC_HOST=localhost:9200
# 驱动
SCOUT_DRIVER=elastic
# 队列配置,数据量大时建议开启
SCOUT_QUEUE=false
生成检索 model
php artisan make:model Models/Article
创建 model 索引配置文件
Elasticsearch\ArticleIndexConfigurator.php
<?php namespace App\Elasticsearch; use ScoutElastic\IndexConfigurator; use ScoutElastic\Migratable; class ArticleIndexConfigurator extends IndexConfigurator { use Migratable; protected $name = 'articles'; /** * @var array */ protected $settings = [ 'analysis' => [ 'analyzer' => [ 'es_std' => [ 'type' => 'standard', 'stopwords' => '_spanish_' ] ] ] ]; }
创建 model 检索规则文件
Elasticsearch\SearchRules\ArticleRule.php
<?php namespace App\Elasticsearch\SearchRules; use ScoutElastic\SearchRule; class ArticleRule extends SearchRule { /* * @inheritdoc */ public function buildHighlightPayload() { return [ 'fields' => [ 'title' => [ 'type' => 'unified', ], 'content' => [ 'type' => 'unified', ], ] ]; } //进行 match 搜索,会分词 public function buildQueryPayload() { $query = $this->builder->query; return [ 'must' => [ 'query_string' => [ 'query' => $query, ], ], ]; } }
设置 model Mapping 及检索字段
class Article extends Model
{
protected $indexConfigurator = ArticleIndexConfigurator::class;
use Searchable;
/**
* 检索规则
* @var string[]
*/
protected $searchRules = [
ArticleRule::class
];
// 设置模型字段的映射关系
protected $mapping = [
'properties' => [
'id' => [
'type' => 'integer',
],
'title' => [
'type' => 'text',
'analyzer' => 'ik_max_word',
'search_analyzer' => 'ik_max_word',
'index_options' => 'offsets',
'store' => true
],
'content' => [
'type' => 'text',
'analyzer' => 'ik_max_word',
'search_analyzer' => 'ik_max_word',
'index_options' => 'offsets',
'store' => true
],
'number' => [
'type' => 'integer',
],
],
];
/**
* 设置 es 检索返回的字段
* @return array
*/
public function toSearchableArray() {
return [
'id' => $this->id,
'title' => $this->title,
'content' => $this->content,
];
}
}
使用步骤
创建索引
php artisan elastic:create-index "App\Elasticsearch\ArticleIndexConfigurator"
更新 elatic 索引类型映射
php artisan elastic:update-mapping "App\Models\Article"
数据库数据导入 elatic
php artisan scout:import "App\Models\Article"
PS: 其他命令
清空 elatic 数据
php artisan scout:flush "App\Models\Article"
使用检索
$query = Article::search('二胡')
->paginateRaw(3,'article',1);
dd($query->items()['hits']);
注意事项
在 laravel 中新增记录、更新记录、删除记录时应严格按照 laravel-soul 文档所述方法去执行
相关文档
部分参考 博客:elasticsearch搜索商品
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: