From 1d22a4b63d41c721e229b710315bc92415fdb9f7 Mon Sep 17 00:00:00 2001 From: Claudio Pinto Date: Wed, 12 Dec 2018 15:00:52 +0000 Subject: [PATCH] Added support for multiple indexes using searchableAs --- src/Engines/ElasticSearchEngine.php | 29 ++++++++++++++++++++++++----- 1 file changed, 24 insertions(+), 5 deletions(-) diff --git a/src/Engines/ElasticSearchEngine.php b/src/Engines/ElasticSearchEngine.php index 9339913..120337b 100644 --- a/src/Engines/ElasticSearchEngine.php +++ b/src/Engines/ElasticSearchEngine.php @@ -10,9 +10,11 @@ use Elasticsearch\Client; +use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Collection; use Laravel\Scout\Builder; use Laravel\Scout\Engines\Engine; +use Laravel\Scout\Searchable; /** * Class ElasticSearchEngine @@ -55,10 +57,11 @@ public function update($models) $params['body'] = []; $models->each( function ($model) use (&$params) { + /** @var Searchable $model */ $params['body'][] = [ 'update' => [ '_id' => $this->getElasticKey($model), - '_index' => $this->index, + '_index' => $this->getIndex($model), '_type' => $model->searchableAs(), ] ]; @@ -83,10 +86,11 @@ public function delete($models) $params['body'] = []; $models->each( function ($model) use (&$params) { + /** @var Searchable $model */ $params['body'][] = [ 'delete' => [ '_id' => $this->getElasticKey($model), - '_index' => $this->index, + '_index' => $this->getIndex($model), '_type' => $model->searchableAs(), ] ]; @@ -197,7 +201,7 @@ public function getTotalCount($results) protected function performSearch(Builder $builder, array $options = []) { $params = [ - 'index' => $this->index, + 'index' => $this->getIndex($builder->model), 'type' => $builder->index ?: $builder->model->searchableAs(), 'body' => [ 'query' => [ @@ -205,7 +209,7 @@ protected function performSearch(Builder $builder, array $options = []) 'must' => [ [ 'query_string' => [ - 'query' => "*{$builder->query}*" + 'query' => !empty(trim($builder->query, '*\s')) ? "*{$builder->query}*" : "*" ] ] ] @@ -270,7 +274,7 @@ function ($value, $key) { } /** - * Generates the sort if theres any. + * Generates the sort if there's any. * * @param Builder $builder * @@ -289,6 +293,11 @@ function ($order) { )->toArray(); } + /** + * @param Searchable|Model $model + * + * @return mixed + */ protected function getElasticKey($model) { if (method_exists($model, 'getScoutKey')) { @@ -297,4 +306,14 @@ protected function getElasticKey($model) return $model->getKey(); } + + /** + * @param Searchable $model + * + * @return string + */ + protected function getIndex($model) + { + return $this->index . '_' . $model->searchableAs(); + } } \ No newline at end of file