laravel 操作elasticsearch

我做了一个导航站(域名是挂路灯的全拼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();

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值