Table of Contents
Install the required components
If composer require laravel/scout reports an error
Then use the command
to modify the configuration file (config/app.php) and add the following Two providers
are added, execute the command, and generate the config file
Modify config/scout.php
Configure the ES account in .env: password@connection
Create a command line file to generate mapping, go to app/Console/Commands
Register this command in the kernel
Execute this command to generate mapping
Modify model to support full-text search
Import full-text index information
Test simple full-text index
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?

Apr 14, 2021 am 10:18 AM
elasticsearch laravel

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
<?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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to get the return code when email sending fails in Laravel? How to get the return code when email sending fails in Laravel? Apr 01, 2025 pm 02:45 PM

Method for obtaining the return code when Laravel email sending fails. When using Laravel to develop applications, you often encounter situations where you need to send verification codes. And in reality...

Laravel schedule task is not executed: What should I do if the task is not running after schedule: run command? Laravel schedule task is not executed: What should I do if the task is not running after schedule: run command? Mar 31, 2025 pm 11:24 PM

Laravel schedule task run unresponsive troubleshooting When using Laravel's schedule task scheduling, many developers will encounter this problem: schedule:run...

In Laravel, how to deal with the situation where verification codes are failed to be sent by email? In Laravel, how to deal with the situation where verification codes are failed to be sent by email? Mar 31, 2025 pm 11:48 PM

The method of handling Laravel's email failure to send verification code is to use Laravel...

How to implement the custom table function of clicking to add data in dcat admin? How to implement the custom table function of clicking to add data in dcat admin? Apr 01, 2025 am 07:09 AM

How to implement the table function of custom click to add data in dcatadmin (laravel-admin) When using dcat...

Laravel Redis connection sharing: Why does the select method affect other connections? Laravel Redis connection sharing: Why does the select method affect other connections? Apr 01, 2025 am 07:45 AM

The impact of sharing of Redis connections in Laravel framework and select methods When using Laravel framework and Redis, developers may encounter a problem: through configuration...

Laravel multi-tenant extension stancl/tenancy: How to customize the host address of a tenant database connection? Laravel multi-tenant extension stancl/tenancy: How to customize the host address of a tenant database connection? Apr 01, 2025 am 09:09 AM

Custom tenant database connection in Laravel multi-tenant extension package stancl/tenancy When building multi-tenant applications using Laravel multi-tenant extension package stancl/tenancy,...

Laravel Eloquent ORM in Bangla partial model search) Laravel Eloquent ORM in Bangla partial model search) Apr 08, 2025 pm 02:06 PM

LaravelEloquent Model Retrieval: Easily obtaining database data EloquentORM provides a concise and easy-to-understand way to operate the database. This article will introduce various Eloquent model search techniques in detail to help you obtain data from the database efficiently. 1. Get all records. Use the all() method to get all records in the database table: useApp\Models\Post;$posts=Post::all(); This will return a collection. You can access data using foreach loop or other collection methods: foreach($postsas$post){echo$post->

Laravel database migration encounters duplicate class definition: How to resolve duplicate generation of migration files and class name conflicts? Laravel database migration encounters duplicate class definition: How to resolve duplicate generation of migration files and class name conflicts? Apr 01, 2025 pm 12:21 PM

A problem of duplicate class definition during Laravel database migration occurs. When using the Laravel framework for database migration, developers may encounter "classes have been used...

See all articles