laravel下使用Elasticsearch驱动+Scout 全文搜索

前期准备:

elasticsearch相关安装:

linux安装

docker安装

安装

composer require laravel/scout
composer require matchish/laravel-scout-elasticsearch

生成 Scout 配置文件 (config/scout.php)

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

指定 Scout 驱动

1、.env 文件添加
SCOUT_DRIVER=Matchish\ScoutElasticSearch\Engines\ElasticSearchEngine
2、或者config/scout.php修改默认驱动
'driver' => env('SCOUT_DRIVER', 'Matchish\ScoutElasticSearch\Engines\ElasticSearchEngine')

#指定 Elasticsearch 服务 IP 端口
ELASTICSEARCH_HOST=192.168.10.10:9200

注册服务

'providers' => [
        /**
         *Elasticsearch全文搜索
         */
     \Matchish\ScoutElasticSearch\ElasticSearchServiceProvider::class
],

清除配置缓存

php artisan config:clear

创建索引配置文件(config/elasticsearch.php)

<?php
return [
    'indices' => [
        'mappings' => [
            'cqc_blog_article' => [ //索引名称
                "properties" => [
                    "markdown" => [
                        "type" => "text",
                        "analyzer" => "ik_max_word", //插入文档时,将text类型的字段做分词然后插入倒排索引,此时就可能用到analyzer指定的分词器
                        "search_analyzer" => "ik_smart" //在查询时,先对要查询的text类型的输入做分词,再去倒排索引搜索,此时就可能用到search_analyzer指定的分词器
                    ],
                    "tags" => [
                        "type" => "text",
                        "analyzer" => "ik_max_word",
                        "search_analyzer" => "ik_smart"
                    ],
                    "title" => [
                        "type" => "text",
                        "analyzer" => "ik_max_word",
                        "search_analyzer" => "ik_smart"
                    ]
                ]
            ]
        ]
    ],
];

//analyzer:字段文本的分词器
//search_analyzer:搜索词的分词器
//根据具体业务场景选择 (颗粒小占用资源多,一般场景 analyzer 使用 ik_max_word,search_analyzer 使用 ik_smart):
//ik_max_word:ik 中文分词插件提供,对文本进行最大数量分词
//福建省厦门市 -> 福建省,福建 , 省 , 厦门市,厦门,门市
//ik_smart: ik 中文分词插件提供,对文本进行最小数量分词
//福建省厦门市 -> 福建省,厦门市

配置文章模型

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Laravel\Scout\Searchable;

class Article extends Model
{
    use Searchable;

    /**
     * Notes:指定索引
     * @return string
     * User: qc DateTime: 2021/9/14 23:11
     */
    public function searchableAs()
    {
        return 'cqc_blog_article';
    }

    /**
     * Notes:设置需要导入索引的字段 (搜索范围:文章内容、标题、标签)
     * @return array
     * User: qc DateTime: 2021/9/14 23:11
     */
    public function toSearchableArray()
    {
        return $this->only('id', 'title', 'markdown','category_id');
    }

    /**
     * Notes:指定 搜索索引中存储的唯一ID (模型主键)
     * @return mixed
     * User: qc DateTime: 2021/9/14 23:11
     */
    public function getScoutKey()
    {
        return $this->id;
    }

    /**
     * Notes:指定 搜索索引中存储的唯一ID的键名
     * @return string
     * User: qc DateTime: 2021/9/14 23:11
     */
    public function getScoutKeyName()
    {
        return 'id';
    }
}

数据导入

Scout 提供了 Artisan 命令 import 用来导入所有已存在的记录到搜索索引
php artisan scout:import "App\Models\Article"
Importing [App\Models\Article]
Switching to the new index
5/5 [⚬⚬⚬⚬⚬⚬⚬⚬⚬⚬⚬⚬⚬⚬⚬⚬⚬⚬⚬⚬⚬⚬⚬⚬⚬⚬⚬⚬] 100%

flush 命令可用于从搜索索引中删除所有模型的记录:
php artisan scout:flush "App\Models\Article"

打开http://192.168.10.10:9100/查看数据是否导入成功

增删改同步测试

/routes/web.php
Route::get('search', function (Request $request) {
//    测试es索引是否会自动同步;
//    复制插入一条
//    $copy = \App\Models\Article::find(17)->replicate();
//    $copy->title='我是复制的docker文章的'.date('Y-m-d H:i:s');
//    $copy->save();
//    dd($rs);

    //测试删除同步
//    $del_test = \App\Models\Article::find(32);
//    $del_test->delete();

    //测试更新
    $update_test = \App\Models\Article::find(30);
    $update_test->title = '我是一条更新的docker文章';
    $update_test->save();
    $rs = \App\Models\Article::search('docker')->get()->toArray();
    dd($rs);
    $request->category_id = 1;
    //测试查询分类
    $rs2 = \App\Models\Article::search($request->category_id)->get()->toArray();
    dump($rs2);

    //测试高亮
    $rs3 = \App\Models\Article::search('docker', function ($client, $body) {
        $higlight = new \ONGR\ElasticsearchDSL\Highlight\Highlight();
        $higlight->addField('title');
        $body->addHighlight($higlight);
        return $client->search(['index' => (new \App\Models\Article())->searchableAs(), 'body' => $body->toArray()]);
    })->raw();
//        ->get()->toArray(); //加->raw()得到原始结果
    dump($rs3);
});

更多操作查看文档

zed
请先登录后发表评论
  • latest comments
  • 总共0条评论