wannanbigpig / laravel-scout-elastic
Laravel Scout 的 Elasticsearch 驱动
v1.1.1
2023-06-02 08:03 UTC
Requires
- php: ^8.0|^8.1|^8.2
- elasticsearch/elasticsearch: ^7.9
- laravel/scout: ^9.3|^10.0
Requires (Dev)
- mockery/mockery: ^1.0
- phpunit/phpunit: ^8.0|^9.3
Suggests
- elasticsearch/elasticsearch: Required to use the Elasticsearch engine (^7.9).
This package is auto-updated.
Last update: 2024-10-01 00:20:39 UTC
README
Laravel Scout 的 Elasticsearch 驱动
安装
您可以通过 composer 安装此包
composer require wannanbigpig/laravel-scout-elastic
设置 Elasticsearch 配置
安装后,您应使用 vendor:publish Artisan 命令发布 Scout 配置文件。此命令将 scout.php 配置文件发布到您的应用程序配置目录
php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"
发布 Laravel Scout 包配置后,您需要将驱动设置为 elasticsearch 并添加其配置
// config/scout.php <?php return [ // ... 'driver' => env('SCOUT_DRIVER', 'elasticsearch'), // ... /* |-------------------------------------------------------------------------- | Elasticsearch Configuration |-------------------------------------------------------------------------- | | Here you may configure your Elasticsearch settings. | */ 'elasticsearch' => [ 'hosts' => [env('ELASTICSEARCH_HOST', 'http://127.0.0.1:9200')], // 'auth' => [ // 'username' => 'elastic', // 'password' => 'password copied during Elasticsearch start', // ], // index_ is followed by the index name. If you do not need to customize the index analyzer, skip the following Settings 'index_article' => [ 'settings' => [ 'number_of_shards' => 5, 'number_of_replicas' => 1, ], 'mappings' => [ "properties" => [ "title" => [ "type" => "text", "analyzer" => "ik_max_word", "search_analyzer" => "ik_smart", "fields" => ["keyword" => ["type" => "keyword", "ignore_above" => 256]], ], ], ], ], ], ];
用法
控制台
// create index
php artisan scout:index article
// delete index
php artisan scout:delete-index article
// batch update data to es
php artisan scout:import "App\Models\Article"
搜索示例
use App\Models\Article; // $condition = "test"; // ... or // $condition = [ // "title" => "test", // "abstract" => "test" // ]; // ... or $keyword = "test"; $source = [1,2]; $startTime = '2023-05-01T00:00:00.000+0800'; $endTime = '2023-05-20T00:00:00.000+0800'; $condition = [ "_customize_body" => 1, "query" => [ "bool" => [ "should" => [ [ "match" => [ "title" => ["query" => $keyword, 'boost' => 5], ], ], [ "match" => [ "abstract" => ["query" => $keyword, 'boost' => 3], ], ], ], "must" => [ [ "terms" => ["source" => $source], ], [ "range" => [ "created_at" => [ 'gte' => $startTime, 'lte' => $endTime, ], ], ], ], ], ], ]; $data = Article::search($condition) ->orderBy('_score', 'desc') ->paginate(10);
更多信息请参阅 Laravel Scout 官方文档.
参考:
https://github.com/ErickTamayo/laravel-scout-elastic
https://github.com/laravel/scout/tree/10.x
https://github.com/medcl/elasticsearch-analysis-ik
许可证
MIT 许可证 (MIT)。