Home > PHP Framework > Laravel > How does Laravel use scout to integrate elasticsearch for full-text search?

How does Laravel use scout to integrate elasticsearch for full-text search?

藏色散人
Release: 2021-04-15 08:57:06
forward
2284 people have browsed it

The following tutorial column from laravel will introduce how Laravel uses scout to integrate elasticsearch for full-text search. I hope it will be helpful to friends in need!

How does Laravel use scout to integrate elasticsearch for full-text search?

Limited to es6.8 version
laravel 5.5 version

Install the required components

composer require tamayo/laravel-scout-elastic
composer require laravel/scout
Copy after login

If composer require laravel/scout reports an error

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.
Copy after login

Then use the command

composer require laravel/scout ^5.0
Copy after login

to modify the configuration file (config/app.php) and add the following Two providers

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

are added, execute the command, and generate the config file

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

Modify config/scout.php

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

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

Configure the ES account in .env: password@connection

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

Create a command line file to generate mapping, go to 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);

    }
}
Copy after login

Register this command in the 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
    ];
Copy after login

Execute this command to generate mapping

 php artisan es:init
Copy after login

Modify model to support full-text search

<?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');
    }

}
Copy after login

Import full-text index information

php artisan scout:import "App\ActivityNews\Model\ActivityNews"
Copy after login

Test simple full-text index

php artisan tinker

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

Related recommendations:The latest five Laravel video tutorials

The above is the detailed content of How does Laravel use scout to integrate elasticsearch for full-text search?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template