Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Custom Algolia Engine for Laravel to only index updated models
<?php
namespace App\Engines;
use Illuminate\Support\Collection;
use Laravel\Scout\Engines\AlgoliaEngine;
class AdvancedAlgoliaEngine extends AlgoliaEngine
{
protected $index;
public function update($models)
{
if ($models->isEmpty()) {
return;
}
$index = $this->algolia->initIndex($models->first()->searchableAs());
if ($this->usesSoftDelete($models->first()) && config('scout.soft_delete', false)) {
$models->each->pushSoftDeleteMetadata();
}
$index->addObjects($models->map(function ($model) {
$array = array_merge(
$model->toSearchableArray(), $model->scoutMetadata()
);
if (empty($array)) {
return;
}
try {
$index = $this->algolia->initIndex($model->searchableAs());
$algoliaObject = $index->getObject($model->getKey());
if ($this->needsUpdate($algoliaObject, $array)) {
return array_merge(['objectID' => $model->getScoutKey()], $array);
}
} catch (\Exception $e) {
if ((int)$e->getCode() == 404) {
return array_merge(['objectID' => $model->getScoutKey()], $array);
}
return;
}
})->filter()->values()->all());
}
public function needsUpdate($algoliaObject, $localObject)
{
if(!isset($algoliaObject['updated_at'])) {
return true;
}
return $algoliaObject['updated_at'] != $localObject['updated_at'] ? true : false;
}
}
@nullthoughts

This comment has been minimized.

Copy link
Owner Author

@nullthoughts nullthoughts commented Jan 16, 2019

Based upon @elfeffe's CustomAlgoliaEngine.php (which recursively compares entire objects) to address Scout's searchable() updating/indexing all records (laravel/scout#226)

Usage and more details: https://nullthoughts.com/development/2019/01/16/custom-algolia-engine/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.