Skip to content

Commit

Permalink
Move ->map() into Query
Browse files Browse the repository at this point in the history
This matches where the search score is set in the Algolia driver.
  • Loading branch information
duncanmcclean committed Nov 2, 2023
1 parent 253f905 commit 98bcfbd
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 13 deletions.
22 changes: 10 additions & 12 deletions src/Meilisearch/Index.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace StatamicRadPack\Meilisearch\Meilisearch;

use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use Meilisearch\Client;
use Meilisearch\Exceptions\ApiException;
Expand Down Expand Up @@ -108,20 +109,15 @@ public function update()
return $this;
}

public function searchUsingApi($query, $options = ['hitsPerPage' => 1000000, 'showRankingScore' => true])
public function searchUsingApi($query, array $options = ['hitsPerPage' => 1000000, 'showRankingScore' => true]): Collection
{
try {
$searchResults = $this->getIndex()->search($query, $options);
} catch (\Exception $e) {
$this->handlemeilisearchException($e, 'searchUsingApi');
$this->handleMeilisearchException($e, 'searchUsingApi');
}

return collect($searchResults->getHits())->map(function ($hit) {
$hit['search_score'] = (int) ceil($hit['_rankingScore'] * 1000);
unset($hit['_rankingScore']);

return $hit;
});
return collect($searchResults->getHits());
}

private function getIndex()
Expand All @@ -137,16 +133,18 @@ private function getDefaultFields(Searchable $entry): array
];
}

private function handlemeilisearchException($e, $method)
/**
* Custom error parsing for Meilisearch exceptions.
*/
private function handleMeilisearchException($e, $method)
{
// custom error parsing for meilisearch exceptions
// Ignore if already created.
if ($e->errorCode === 'index_already_exists' && $method === 'createIndex') {
// ignore if already created
return true;
}

// Ignore if not found.
if ($e->errorCode === 'index_not_found' && $method === 'deleteIndex') {
// ignore if not found
return true;
}

Expand Down
8 changes: 7 additions & 1 deletion src/Meilisearch/Query.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,12 @@ class Query extends QueryBuilder
{
public function getSearchResults($query)
{
return $this->index->searchUsingApi($query);
$results = $this->index->searchUsingApi($query);

return $results->map(function ($result, $i) {
$result['search_score'] = (int) ceil($result['_rankingScore'] * 1000);

return $result;
});
}
}

0 comments on commit 98bcfbd

Please sign in to comment.