搜索实现(scout/elasticsearch)

益麻雀
2023-12-01

1、elasticsearch安装

前提条件:必须安装jdk
安装

elasticsearch——composer require elasticsearch

2、scout安装

如果laravel版本是5.8则
1、运行

composer reuqire laravel/scout ^6.0

2、在config/app.php配置文件中的providers数组加入:

Laravel\Scout\ScoutServiceProvider::class

3、运行

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

会在config下生成scout.php文件

4、运行

composer require tamayo/laravel-scout-elastic

在config/app下配置:

ScoutEngines\Elasticsearch\ElasticsearchProvider::class,
 		Laravel\Scout\ScoutServiceProvider::class,
        ScoutEngines\Elasticsearch\ElasticsearchProvider::class,

5、修改scout.php文件

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

'elasticsearch' => [
        'index' => env('ELASTICSEARCH_INDEX', 'laravel'),
        'hosts' => [
            env('ELASTICSEARCH_HOST', 'http://localhost:9200'),
        ],
   ],

3、建索引和模版

1、运行php artisan make:command ESInit
2、在ESInit.php中修改文件内容
运行

composer require guzzlehttp/guzzle
use GuzzleHttp\Client;//拓展包

protected $signature = 'es:init';

public function handle()
    {
        //
        $client = new Client();
        // 创建模版
        $url = config('scout.elasticsearch.hosts')[0] . '/_template/tmp';
       
        $client->put($url, [
            'json' => [
                'template' => config('scout.elasticsearch.index'),
                'settings' => [
                    'number_of_shards' => 1
                ],
                'mappings' => [
                    '_default_' => [
                        '_all' => [
                            'enabled' => true
                        ],
                        'dynamic_templates' => [
                            [
                                'strings' => [
                                    'match_mapping_type' => 'string',
                                    'mapping' => [
                                        'type' => 'text',
                                        'analyzer' => 'ik_smart',
                                        'ignore_above' => 256,
                                        'fields' => [
                                            'keyword' => [
                                                'type' => 'keyword'
                                            ]
                                        ]
                                    ]
                                ]
                            ]
                        ]
                    ]
                ]
            ]
        ]);
        // 为了方便看到执行结果
        $this->info("======= 创建模板成功 =======");
        $url = config('scout.elasticsearch.hosts')[0] . '/' . config('scout.elasticsearch.index');
       
        $client->put($url, [
            'json' => [
                'settings' => [
                    'refresh_interval' => '5s',
                    'number_of_shards' => 1,
                    'number_of_replicas' => 0,
                ],
                'mappings' => [
                    '_default_' => [
                        '_all' => [
                            'enabled' => false
                        ]
                    ]
                ]
            ]
        ]);
        // 为了方便看到执行结果
        $this->info("======= 创建索引成功 =======");
    }

然后在app\Console\kernel.php中的protected $commends=[]加入以下代码

 \App\Console\Commands\ESInit::class

4、运行语句——php artisan es:init

php artisan es:init
======= 创建模板成功 =======
======= 创建索引成功 =======

5、在model中引入方法

use Laravel\Scout\Searchable;//包

use Searchable;
    //定义索引礼貌的类型
    public function searchableAs()
    {
        return "post";
    }
    //定义有哪些字段需要搜索
    public function toSearchableArray()
    {
        return [
            'title' => $this->title,
            'content' => $this->context,
        ];
    }

4、导入数据

运行代码——php artisan scout:import “模型名”

$ php artisan scout:import "\App\Post"
Imported [\App\Post] models up to ID: 18
All [\App\Post] records have been imported.

5、实现逻辑

1、首先新建一个路由(需确定路由的优先级问题)
2、在控制器内新建对应的路由方法

 		//验证
        $this->validate(request(),[
            'query' => 'required'
        ]);
        //逻辑
        $query = request("query");
        $posts = \App\Post::search($query)->paginate(2);
        //渲染
        return view("post/search",compact('posts','query'));

3、前端完成

1、在本人自己安装的实话,出现了版本不匹配问题
2、在导入数据的时候,数据导入不成功——大概的原因是由于插件没有安装完整(tamayo/laravel-scout-elastic)
3、在搜索的时候,点击按钮事件,跳转不过去——原因是由于前端页面没有写表单

问题

Elasticsearch \ Common \ Exceptions \ Missing404Exception (404)
{"error":{"root_cause":[{"type":"index_not_found_exception","reason":"no such index","resource.type":"index_or_alias","resource.id":"laravel","index_uuid":"_na_","index":"laravel"}],"type":"index_not_found_exception","reason":"no such index","resource.type":"index_or_alias","resource.id":"laravel","index_uuid":"_na_","index":"laravel"},"status":404}

原因可能是需要重新导入数据——php artisan scout:import “\App\Post”

 类似资料: