Skip to content
This repository has been archived by the owner on Nov 4, 2021. It is now read-only.

Allow BulkIndexer to load relations efficiently when called from a queue #212

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions src/Console/stubs/searchable_model.stub
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,11 @@ class DummyClass extends Model
protected $mapping = [
//
];

/**
* @var array
*/
public $searchableRelations = [
//
];
}
36 changes: 19 additions & 17 deletions src/Indexers/BulkIndexer.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ public function update(Collection $models)
{
$model = $models->first();
$indexConfigurator = $model->getIndexConfigurator();
$relations = $model->searchableRelations ?? [];

$bulkPayload = new TypePayload($model);

Expand All @@ -28,27 +29,28 @@ public function update(Collection $models)
$bulkPayload->set('refresh', $documentRefresh);
}

$models->each(function ($model) use ($bulkPayload) {
if ($model::usesSoftDelete() && config('scout.soft_delete', false)) {
$model->pushSoftDeleteMetadata();
}
$models->loadMissing($relations)
->each(function ($model) use ($bulkPayload) {
if ($model::usesSoftDelete() && config('scout.soft_delete', false)) {
$model->pushSoftDeleteMetadata();
}

$modelData = array_merge(
$model->toSearchableArray(),
$model->scoutMetadata()
);
$modelData = array_merge(
$model->toSearchableArray(),
$model->scoutMetadata()
);

if (empty($modelData)) {
return true;
}
if (empty($modelData)) {
return true;
}

$actionPayload = (new RawPayload())
->set('index._id', $model->getKey());
$actionPayload = (new RawPayload())
->set('index._id', $model->getKey());

$bulkPayload
->add('body', $actionPayload->get())
->add('body', $modelData);
});
$bulkPayload
->add('body', $actionPayload->get())
->add('body', $modelData);
});

ElasticClient::bulk($bulkPayload->get());
}
Expand Down