Laravel combined Elasticsearch full-text search

First, install

Run terminal, the global installation elasticsearch, the following command:

brew install elasticsearch

Process, you'll see an error message that says you do not have Javathe JDK, but must be version 1.8 or higher, can be installed from the command prompt.

brew cask install homebrew/cask-versions/java8

After installation, execute the command to view the version information:java -version

Then brew services start elasticsearchyou can start the service.

Second, create a test project

1, the local terminal execute the command: laravel new blogcreate a new project, normal access to the virtual machine configuration.
2, modify the route web.php, as follows:

Route::get('/', 'HomeController@index');

3, creates a corresponding controller and method, execute the command: php artisan make:controller HomeController
4, .envfile configuration database, and create a database, and insert the data in the table.
5, create a model: php artisan make:model Art
6, in HomeControllerthe controller of indexthe writing process the following code:

return Art::search('天')->get();

Remember above use App\Art;

Third, the configuration elasticsearch

1, the terminal into the current project folder, execute the command: composer require tamayo/laravel-scout-elastic
2, then create a profile: php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"
3, modify the configuration file information:

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

Of course, the configuration information can also be configured to the .envfile.

4, modification Artmodel code as follows:

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;
use Laravel\Scout\Searchable;

class Art extends Model
{
    use Searchable;
}

5, the index introduced:php artisan scout:import "App\Art"

6, test 1, based on the above operation, we have to refresh your browser, you'll see the miracle has been born:

Test 2, as modified controller code

return Art::search('今天')->get();

The results are as follows:

At this point, full-text search has been achieved. There are other operations, such as querying, paging, etc., you can refer to the Laravelofficial documentation. The next step is to apply to real projects, follow-up perfect.

references:
https://laravelacademy.org/post/9599.html
https://github.com/ErickTamayo/laravel-scout-elastic

Published 14 original articles · won praise 1 · views 91

Guess you like

Origin blog.csdn.net/huangdj321/article/details/104929532