laravel 操作elasticsearch

贝镜
2023-12-01

我做了一个导航站(域名是挂路灯的全拼gualudeng.com),里面精选了各种影视,动漫,黑科技,实用工具,搞笑有趣的站点,动动大家可爱的小手,点进来看看吧,良心站点。

1.安装相应插件

composer require elasticsearch/elasticsearch
composer require laravel/scout
composer require matchish/laravel-scout-elasticsearch
//发布配置文件
php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"
//在config/scout.php配置文件中修改搜索驱动为es
'driver' => env('SCOUT_DRIVER', 'Matchish\ScoutElasticSearch\Engines\ElasticSearchEngine')
//在.env 配置文件中添加ip
ELASTICSEARCH_HOST=172.17.0.1:9200   //带密码http://username:password@host:port
在app.php中添加服务
\Matchish\ScoutElasticSearch\ElasticSearchServiceProvider::class

2.配置索引格式(新建文件 config/elasticsearch)修改配置后要清除缓存 php artisan config:clear

<?php
return [
 'indices' => [
     'mappings' => [
         'articles' => [
             "properties"=>  [
                 "content"=>  [
                     "type"=>  "text",
                     "analyzer"=>  "ik_max_word",
                     "search_analyzer"=>  "ik_smart"
                 ],
                 "tags"=>  [
                     "type"=>  "text",
                     "analyzer"=>  "ik_max_word",
                     "search_analyzer"=>  "ik_smart"
                 ],
                 "title"=>  [
                     "type"=>  "text",
                     "analyzer"=>  "ik_max_word",
                     "search_analyzer"=>  "ik_smart"
                 ]
             ]
         ]
     ]
 ],
];

3.在模型中使用信笺

use Searchable;
//关联索引(配置文件中的)
public function searchableAs()
{
    return 'articles';
}
//设置需要在es中存入的字段
public function toSearchableArray()
{
    return [
            'content' => ArticleContent::query()
                ->where('article_id',$this->id)
                ->value('content'),
            'tags'    => implode(',',$this->tags),
            'title'   => $this->title
        ];
    }

//指定id
public function getScoutKey()
 {
     return $this->id;
 }

public function getScoutKeyName()
 {
     return 'id';
 }

4.导入本地数据

php artisan scout:import
php artisan scout:import "App\Models\Blog\Article"   //导入指定模型

5.复杂搜索代码

$data = Report::search("classify:".$classify->name,function($client)use($date,$n_date,$offset,$limit){
            $params['query']['bool']['must']['match']=['classify' => '信息技术'];
            if($date){
                $params['query']['bool']['filter']['range']=["publish_time"=>["gt"=>$date,"lt"=>$n_date]];
            }
            $params['sort']=["publish_time"=>'desc'];
            $params['from'] = $offset;
            $params['size'] = $limit;
            return $client->search(['index' => 'reports', 'body' => $params]);
        })->get()->toArray();

 类似资料: