Skip to content

Instantly share code, notes, and snippets.

@elfeffe
Created May 15, 2018 19:55
Show Gist options
  • Save elfeffe/54d4125447f0b7d65620a79a0efe165e to your computer and use it in GitHub Desktop.
Save elfeffe/54d4125447f0b7d65620a79a0efe165e to your computer and use it in GitHub Desktop.
<?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
Copy link
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