Laravel Scout Aggregator for Typesense extends Laravel Scout with support for aggregated search across multiple models using Typesense. Based on Algolia's Scout Extended package, it adapts and extends the aggregator functionality for the open-source Typesense engine.
You can install the package via composer:
composer require needbrainz/scout-typesense-aggregatorTo create a new aggregator, you can use the make:aggregator command:
php artisan make:typesense-aggregator MyAggregator<?php
namespace App\Search;
use NeedBrainz\TypesenseAggregator\TypesenseAggregator;
class MyAggregator extends TypesenseAggregator
{
/**
* The names of the models that should be aggregated.
*
* @var string[]
*/
protected $models = [
App\Models\MyModel::class,
App\Models\MyOtherModel::class,
];
}Then configure the aggregator settings in your config/scout.php file:
'typesense' => [
'model-settings' => [
MyAggregator::class => [
'collection-schema' => [
'fields' => [
[
'name' => 'id',
'type' => 'string',
],
// Your aggregated fields
[
'name' => 'name',
'type' => 'string',
],
[
'name' => 'description',
'type' => 'string',
],
[
'name' => 'created_at',
'type' => 'int64',
],
],
'default_sorting_field' => 'created_at',
],
'search-parameters' => [
'query_by' => 'name,description',
]
],
]Register your Aggregator in an appropriate service provider, such as App\Providers\AppServiceProvider:
use App\Search\MyAggregator;
public function boot(): void
{
MyAggregator::bootSearchable();
}By default the Aggregator will merge the models toSearchableArrray and set the custom id coming from the Aggregator getScoutKey($model) which will create an id in the format ModelClassName::ModelScoutKey. This format can then be reverted with the extractScoutKey($key) for models retrieve. So if you change the syntax, don't forget to override the getScoutKey and extractScoutKey methods in your Aggregator class.
If the structure of the models is different, you can override the toSearchableArray method in your Aggregator class to customize the merging of the models.
public function toSearchableArray(): array
{
$array = [
'id' => (string )$this->getScoutKey(),
'created_at' => $this->model->created_at->timestamp,
// default empty values
'name' => '',
'description' => '',
];
// Customize the merging of the models here
if ($this->model instanceof MyModel) {
$array['name'] = (string) $this->model->name;
$array['description'] = (string) $this->model->description;
} elseif ($this->model instanceof MyOtherModel) {
$array['name'] = (string) $this->model->title;
$array['description'] = (string) $this->model->summary;
}
return $array;
}composer testPlease see CHANGELOG for more information on what has changed recently.
Please see CONTRIBUTING for details.
Please review our security policy on how to report security vulnerabilities.
The MIT License (MIT). Please see License File for more information.