首页  >  文章  >  php框架  >  Laravel怎么使用scout集成elasticsearch做全文搜索

Laravel怎么使用scout集成elasticsearch做全文搜索

藏色散人
藏色散人转载
2021-04-14 10:18:392213浏览

下面由laravel教程栏目给大家介绍Laravel怎么使用scout集成elasticsearch做全文搜索,希望对需要的朋友有所帮助!

Laravel怎么使用scout集成elasticsearch做全文搜索

仅限于 es6.8版本
laravel 5.5版本

安装需要的组件

composer require tamayo/laravel-scout-elastic
composer require laravel/scout

如果composer require laravel/scout 出现报错

Using version ^6.1 for laravel/scout
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - tamayo/laravel-scout-elastic 4.0.0 requires laravel/scout ^5.0 -> satisfiable by laravel/scout[5.0.x-dev].
    - tamayo/laravel-scout-elastic 4.0.0 requires laravel/scout ^5.0 -> satisfiable by laravel/scout[5.0.x-dev].
    - tamayo/laravel-scout-elastic 4.0.0 requires laravel/scout ^5.0 -> satisfiable by laravel/scout[5.0.x-dev].
    - Conclusion: don't install laravel/scout 5.0.x-dev
    - Installation request for tamayo/laravel-scout-elastic ^4.0 -> satisfiable by tamayo/laravel-scout-elastic[4.0.0].


Installation failed, reverting ./composer.json to its original content.

那么使用命令

composer require laravel/scout ^5.0

修改一下配置文件(config/app.php),添加如下两个provider

'providers' => [  
        //es search 加上以下内容  
        Laravel\Scout\ScoutServiceProvider::class,  
        ScoutEngines\Elasticsearch\ElasticsearchProvider::class,  
]

添加完成,执行命令,生成config文件

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

修改config/scout.php

    'driver' => env('SCOUT_DRIVER', 'elasticsearch'),

    'elasticsearch' => [
        'index' => env('ELASTICSEARCH_INDEX', '你的Index名字'),
        'hosts' => [
            env('ELASTICSEARCH_HOST', ''),
        ],
    ],

在.env 配置ES的 账号:密码@连接

ELASTICSEARCH_HOST=elastic:密码@你的域名.com:9200

创建一个生成mapping的命令行文件,到 app/Console/Commands

<?php
namespace App\Console\Commands;
use GuzzleHttp\Client;
use Illuminate\Console\Command;

class ESInit extends Command {

    protected $signature = &#39;es:init&#39;;

    protected $description = &#39;init laravel es for news&#39;;

    public function __construct() { parent::__construct(); }

    public function handle() { //创建template
        $client = new Client([&#39;auth&#39;=>['elastic', 'yourPassword']]);
        $url = config('scout.elasticsearch.hosts')[0] . '/_template/news';
        $params = [
            'json' => [
                'template' => config('scout.elasticsearch.index'),
                'settings' => [
                    'number_of_shards' => 5
                ],
                'mappings' => [
                    '_default_' => [
                        'dynamic_templates' => [
                            [
                                'strings' => [
                                    'match_mapping_type' => 'string',
                                    'mapping' => [
                                        'type' => 'text',
                                        'analyzer' => 'ik_smart',
                                        'ignore_above' => 256,
                                        'fields' => [
                                            'keyword' => [
                                                'type' => 'keyword'
                                            ]
                                        ]
                                    ]
                                ]
                            ]
                        ]
                    ]
                ]
            ]
        ];
        $client->put($url, $params);

        // 创建index
        $url = config('scout.elasticsearch.hosts')[0] . '/' . config('scout.elasticsearch.index');

        $params = [
            'json' => [
                'settings' => [
                    'refresh_interval' => '5s',
                    'number_of_shards' => 5,
                    'number_of_replicas' => 0
                ],
                'mappings' => [
                    '_default_' => [
                        '_all' => [
                            'enabled' => false
                        ]
                    ]
                ]
            ]
        ];
        $client->put($url, $params);

    }
}

在kernel中注册这个命令

<?php

namespace App\Console;

use App\Console\Commands\ESInit;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        ESInit::class
    ];

执行这个命令 生成 mapping

 php artisan es:init

修改model支持 全文搜索

<?php
namespace App\ActivityNews\Model;

use App\Model\Category;
use App\Star\Model\Star;
use Illuminate\Database\Eloquent\Model;
use Laravel\Scout\Searchable;


class ActivityNews extends Model
{
    use Searchable;

    protected $table = &#39;activity_news&#39;;
    protected $fillable = [
        &#39;type_id&#39;,
        &#39;category_id&#39;,
        &#39;title&#39;,
        &#39;sub_title&#39;,
        &#39;thumb&#39;,
        &#39;intro&#39;,
        &#39;star_id&#39;,
        &#39;start_at&#39;,
        &#39;end_at&#39;,
        &#39;content&#39;,
        &#39;video_url&#39;,
        &#39;status&#39;,
        &#39;is_open&#39;,
        &#39;is_top&#39;,
        &#39;rank&#39;,
    ];

    public function star()
    {
        return $this->hasOne(Star::class, 'id', 'star_id');
    }

    public function category()
    {
        return $this->hasOne(Category::class, 'id', 'category_id');
    }

    public static function getActivityIdByName($name)
    {
        return self::select('id')
            ->where([
                ['status', '=', 1],
                ['type_id', '=', 2],
                ['title', 'like', '%' . $name . '%']
            ])->get()->pluck('id');
    }

}

导入全文索引信息

php artisan scout:import "App\ActivityNews\Model\ActivityNews"

测试简单的全文索引

php artisan tinker

>>> App\ActivityNews\Model\ActivityNews::search('略懂皮毛')->get();

相关推荐:最新的五个Laravel视频教程

以上是Laravel怎么使用scout集成elasticsearch做全文搜索的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:segmentfault.com。如有侵权,请联系admin@php.cn删除