Skip to content
This repository was archived by the owner on Nov 4, 2021. It is now read-only.

Add option to return ElasticSearch score #415

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
20 changes: 20 additions & 0 deletions src/Builders/FilterBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down Expand Up @@ -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.
*
Expand Down
8 changes: 7 additions & 1 deletion src/ElasticEngine.php
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -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']);
}
Expand Down
9 changes: 8 additions & 1 deletion src/Searchable.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down