Skip to content

Instantly share code, notes, and snippets.

@nullthoughts
Created January 16, 2019 17:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nullthoughts/dd761e5c7de46d78a9be3b9fbf750c57 to your computer and use it in GitHub Desktop.
Save nullthoughts/dd761e5c7de46d78a9be3b9fbf750c57 to your computer and use it in GitHub Desktop.
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
Copy link
Author

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