Created
January 16, 2019 17:48
-
-
Save nullthoughts/dd761e5c7de46d78a9be3b9fbf750c57 to your computer and use it in GitHub Desktop.
Custom Algolia Engine for Laravel to only index updated models
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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/