Sử dụng elasticsearch để xử lý việc tìm kiếm trong laravel 11
Elasticsearch là một công cụ tìm kiếm mạnh mẽ và linh hoạt, được thiết kế để xử lý các yêu cầu tìm kiếm phức tạp một cách nhanh chóng và hiệu quả. Việc tích hợp Elasticsearch vào Laravel 11 có thể nâng cao khả năng tìm kiếm của ứng dụng web của bạn, giúp tìm kiếm dữ liệu lớn một cách nhanh chóng và chính xác.
Bước 1 : Tạo laravel app
Chúng ta tạo 1 laravel 11 app với câu lệnh :
composer create-project laravel/laravel la11elasticsearch
Bước 2 : Tạo demo post
Chúng ta tạo dữ liệu demo với câu lệnh :
php artisan make:model Post --all
Bước 3 : Tạo seeder
Trong file database/factories/PostFactory.php code như sau :
<?php namespace Database\Factories; use Illuminate\Database\Eloquent\Factories\Factory; /** * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Post> */ class PostFactory extends Factory { /** * Define the model's default state. * * @return array<string, mixed> */ public function definition(): array { return [ 'name'=>fake()->title(), 'content'=>fake()->paragraph(5), 'description'=>fake()->paragraph(2), ]; } }
Trong file database/seeders/PostSeeder.php :
<?php namespace Database\Seeders; use App\Models\Post; use Illuminate\Database\Console\Seeds\WithoutModelEvents; use Illuminate\Database\Seeder; class PostSeeder extends Seeder { /** * Run the database seeds. */ public function run(): void { Post::factory()->count(200)->create(); } }
Trong file database/seeders/DatabaseSeeder.php
<?php namespace Database\Seeders; use App\Models\Post; use App\Models\User; // use Illuminate\Database\Console\Seeds\WithoutModelEvents; use Illuminate\Database\Seeder; class DatabaseSeeder extends Seeder { /** * Seed the application's database. */ public function run(): void { // User::factory(10)->create(); // User::factory()->create([ // 'name' => 'Test User', // 'email' => '[email protected]', // ]); $this->call([ PostSeeder::class, ]); } }
Sau đó chúng ta chạy lệnh :
php artisan db:seed
Bước 4 Cài đặt scout
Cài đặt scout với lệnh sau :
composer require laravel/scout
Xuất bản cấu hình scout với lệnh sau :
php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"
vào file .env thêm dòng sau :
SCOUT_DRIVER=elastic
Bước 5 : Cài đặt Next-gen Elasticsearch
Chạy lệnh sau :
composer require jeroen-g/explorer
Xuất bản file config với command sau :
php artisan vendor:publish --tag=explorer.config
Laravel sẽ tạo file config/explorer.php :
Chúng ta tùy chỉnh file như sau :
<?php declare(strict_types=1); return [ /* * There are different options for the connection. Since Explorer uses the Elasticsearch PHP SDK * under the hood, all the host configuration options of the SDK are applicable here. See * https://www.elastic.co/guide/en/elasticsearch/client/php-api/current/configuration.html */ 'connection' => [ 'host' => env('ELASTICSEARCH_HOST','localhost'), 'port' => '9200', 'scheme' => 'http', 'auth' => [ 'username' => env('ELASTICSEARCH_USERNAME'), 'password' => env('ELASTICSEARCH_PASSWORD') ], ], /** * The default index settings used when creating a new index. You can override these settings * on a per-index basis by implementing the IndexSettings interface on your model or defining * them in the index configuration below. */ 'default_index_settings' => [ //'index' => [], //'analysis' => [], ], /** * An index may be defined on an Eloquent model or inline below. A more in depth explanation * of the mapping possibilities can be found in the documentation of Explorer's repository. */ 'indexes' => [ // \App\Models\Post::class ], /** * You may opt to keep the old indices after the alias is pointed to a new index. * A model is only using index aliases if it implements the Aliased interface. */ 'prune_old_aliases' => true, /** * When set to true, sends all the logs (requests, responses, etc.) from the Elasticsearch PHP SDK * to a PSR-3 logger. Disabled by default for performance. */ 'logging' => env('EXPLORER_ELASTIC_LOGGER_ENABLED', false), 'logger' => null, ];
Cập nhật file .env :
SCOUT_DRIVER=elastic SCOUT_PREFIX=truyenvideo.com ELASTICSEARCH_HOST=xxxxx ELASTICSEARCH_USERNAME=xxxx ELASTICSEARCH_PASSWORD=xxxxx
Bước 6 : Cập nhật lại file model Post và file config/explorer.php :
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use JeroenG\Explorer\Application\Explored; use Laravel\Scout\Searchable; class Post extends Model implements Explored { use HasFactory,Searchable; // protected $guarded=['id']; protected $fillable=['name','content','description']; public function mappableAs() { return [ 'id' => 'keyword', 'name' => 'text', ]; } }
File config/explorer.php thêm cấu hình vào indexes :
'indexes' => [ // \App\Models\Post::class \App\Models\Post::class, ],
Và cuối cùng chúng ta chạy lệnh :
php artisan scout:import App\Models\Post
để import dữ liệu lên elastic .
Sau đó ta dễ dàng sử dụng với phương thức search như ví dụ sau :
$data = Post::search('Prof.')->get(); return response()->json($data);
Vậy là chúng ta đã có thể sử dụng elastic search 1 cách đơn giản .Link code github demo các bạn có thể tham khảo ở dưới đây