savks / e-search
2.5.1
2024-09-17 14:46 UTC
Requires
- php: ^8.1
- elasticsearch/elasticsearch: ~8.0
README
ESearch
安装
步骤 1
安装包
composer require savks/e-search
步骤 2
发布 e-search 配置文件
php artisan vendor:publish
用法
步骤 1
根据以下示例创建资源类,以便将数据映射到特定的 Elasticsearch 索引
<?php namespace App\ESearch\Resources; use Closure; use App\Models\Product; use Illuminate\Support\Arr; use Illuminate\Support\Collection; use Savks\ESearch\Support\Resource; use Savks\ESearch\Support\Config; class ProductResource extends Resource { public static function id(): string { return 'product'; } public static function configure(Config $config): void { // } public function seed(?array $ids, int $limit, Closure $callback, Closure $resolveCount, array $criteria = []): void { $query = Product::query() ->with([ 'categories', ]); if ($ids) { $query->whereIn('id', $ids); } $resolveCount( $query->count() ); $query->chunk($limit, $callback); } public function clean(int $limit, Closure $callback, Closure $resolveCount, array $criteria = []): void { } public function mapTo(array $result): Collection { $ids = Arr::pluck($result['hits']['hits'], '_source.id'); return Product::whereIn($ids) ->sortBy(function (Product $vehicle) use ($ids) { return \array_search($vehicle->id, $ids, true); }) ->values(); } public function buildDocument($vehicle): array { $isActive = $product->category_id && $product->is_active && $product->category->is_active; $data = [ 'id' => $product->id, 'name_uk' => $product->getTranslation('name', 'uk'), 'name_ru' => $product->getTranslation('name', 'ru'), 'manufacturer_code' => mb_strtolower($product->manufacturer_code), 'price' => $product->price, 'category_id' => $product->categories->pluck('id'), 'views' => $product->views ?: 0, 'available' => $product->available, 'is_active' => $isActive ? 1 : 0, ]; return $data; } public function mapping(): array { return [ 'properties' => [ 'name_uk' => [ 'type' => 'text', // 'analyzer' => 'ukrainian', ], 'name_ru' => [ 'type' => 'text', // 'analyzer' => 'russian', ], 'manufacturer_code' => [ 'type' => 'keyword' ], 'price' => [ 'type' => 'scaled_float', 'scaling_factor' => 100, ], 'category_id' => [ 'type' => 'long' ], 'views' => [ 'type' => 'integer' ], 'available' => [ 'type' => 'boolean' ], 'is_active' => [ 'type' => 'boolean' ], ] ]; } private function calcWeight(Vehicle $vehicle): int { } }
步骤 2
将您的索引资源添加到 "resources" 部分的 e-search 配置中
return [ 'resources' => [ 'product' => App\ESearch\Resources\ProductResource::class, // or App\ESearch\Resources\ProductResource::class, ], ]