Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
namespace App\Engines;
use Laravel\Scout\Engines\AlgoliaEngine;
use Log;
class AdvancedAlgoliaEngine extends AlgoliaEngine
{
protected $index;
/**
* Update the given model in the index.
*
* @param \Illuminate\Database\Eloquent\Collection $models
* @throws \AlgoliaSearch\AlgoliaException
* @return void
*/
public function update($models)
{
foreach ($models as $model) {
// We need to get the index for each model, because it can change
$index = $this->algolia->initIndex($model->searchableAs());
$array = $model->toSearchableArray();
try {
$algoliaObject = $index->getObject($model->getKey());
// If we have changes, and $array ($model) is not empty, we update
if ($this->arrayRecursiveDiff($array, $algoliaObject) && !empty($array)) {
array_merge(['objectID' => $model->getKey()], $array);
$result = $index->saveObject(
$array
);
}
} catch (\Exception $e) {
if ((int)$e->getCode() == 404) {
// It gives error when doesn't exist, so if error we update (add)
array_merge(['objectID' => $model->getKey()], $array);
$result = $index->addObject(
$array
);
} else {
Log::warning('Error was: ' . print_r($e, true));
}
}
}
}
/**
* Get the difference of arrays recursively
*
* @param array $aArray1
* @param array $aArray2
* @return array
*/
function arrayRecursiveDiff($aArray1, $aArray2) {
$aReturn = array();
foreach ($aArray1 as $mKey => $mValue) {
if (array_key_exists($mKey, $aArray2)) {
if (is_array($mValue)) {
$aRecursiveDiff = $this->arrayRecursiveDiff($mValue, $aArray2[$mKey]);
if (count($aRecursiveDiff)) { $aReturn[$mKey] = $aRecursiveDiff; }
} else {
if ($mValue != $aArray2[$mKey]) {
$aReturn[$mKey] = $mValue;
}
}
} else {
$aReturn[$mKey] = $mValue;
}
}
return $aReturn;
}
/**
* Remove the given model from the index.
*
* @param \Illuminate\Database\Eloquent\Collection $models
* @return void
*/
public function delete($models)
{
foreach ($models as $model) {
$index = $this->algolia->initIndex($model->searchableAs());
$index->deleteObject($model->getKey());
}
}
}
@elfeffe

This comment has been minimized.

Copy link
Owner Author

elfeffe commented May 15, 2018

You have to remove some fields in MongoDB, _id for example.
Some tuning is needed in the model to unset some fields and avoid duplication

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.