diff --git a/README.md b/README.md index 91589cfb..d953bf5b 100644 --- a/README.md +++ b/README.md @@ -294,6 +294,17 @@ $model = App\MyModel::search('sales') $model->sortPayload; ``` +And return the score assigned by ElasticSearch with the models: + +```php +$model = App\MyModel::search('sales') + ->withScores() + ->get(); + +// To retrieve the score, use model \`_score\` attribute: +$model->_score; +``` + At last, if you want to send a custom request, you can use the `searchRaw` method: diff --git a/src/Builders/FilterBuilder.php b/src/Builders/FilterBuilder.php index 5f47fa53..e385730e 100644 --- a/src/Builders/FilterBuilder.php +++ b/src/Builders/FilterBuilder.php @@ -53,6 +53,13 @@ class FilterBuilder extends Builder */ public $minScore; + /** + * Determines if the score should be returned with the model. + * + * @var bool - false + */ + public $withScores = false; + /** * FilterBuilder constructor. * @@ -593,6 +600,19 @@ public function minScore($score) return $this; } + /** + * Set the withScores property. + * + * @param bool $withScores - true + * @return $this + */ + public function withScores($withScores = true) + { + $this->withScores = $withScores; + + return $this; + } + /** * Get the count. * diff --git a/src/ElasticEngine.php b/src/ElasticEngine.php index 4cd2af2c..c38cbc55 100755 --- a/src/ElasticEngine.php +++ b/src/ElasticEngine.php @@ -306,6 +306,8 @@ public function map(Builder $builder, $results, $model) $columns[] = $scoutKeyName; } + $withScores = $builder->withScores; + $ids = $this->mapIds($results)->all(); $query = $model::usesSoftDelete() ? $model->withTrashed() : $model->newQuery(); @@ -319,12 +321,16 @@ public function map(Builder $builder, $results, $model) ->keyBy($scoutKeyName); $values = Collection::make($results['hits']['hits']) - ->map(function ($hit) use ($models) { + ->map(function ($hit) use ($models, $withScores) { $id = $hit['_id']; if (isset($models[$id])) { $model = $models[$id]; + if ($withScores && isset($hit['_score'])) { + $model->_score = $hit['_score']; + } + if (isset($hit['highlight'])) { $model->highlight = new Highlight($hit['highlight']); } diff --git a/src/Searchable.php b/src/Searchable.php index bd5da477..ec448a02 100644 --- a/src/Searchable.php +++ b/src/Searchable.php @@ -15,12 +15,19 @@ trait Searchable } /** - * The highligths. + * The highlights. * * @var \ScoutElastic\Highlight|null */ private $highlight = null; + /** + * The score returned from elasticsearch. + * + * @var float|null + */ + public $_score; + /** * Get the index configurator. *