简体   繁体   中英

Laravel - Elastic Search

I have been using https://github.com/babenkoivan/scout-elasticsearch-driver and I am looking to set "track_total_hits" to true so I can get the total results.

https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-body.html#request-body-search-track-total-hits

I am not sure how to get an array value to that point?

Thanks.

The package you are using is not implementing the track_total_hits (a search on the repo content will confirm that). You can, however, fork the repo and add the functionality yourself if required.

I had the same issue, to solve it, I created my own implementation to include track_total_hits and more…, using callback Closure.

  1. Extend SearchRequestFactory
use ElasticScoutDriver\Factories\SearchRequestFactory;
use ElasticAdapter\Search\SearchRequest;
use Laravel\Scout\Builder;

class ElasticSearchRequestFactory extends SearchRequestFactory
{
    public function makeFromBuilder(Builder $builder, array $options = []): SearchRequest
    {
        $searchRequest = parent::makeFromBuilder($builder, $options);

        if ($builder->callback) {
            call_user_func($builder->callback, $searchRequest, $builder);
        }

        return $searchRequest;
    }
}
  1. Register extended SearchRequestFactory in AppServiceProvider
public function register()
{
    $this->app->bind(SearchRequestFactoryInterface::class, ElasticSearchRequestFactory::class, true);
}
  1. Set values using SearchRequest
use ElasticAdapter\Search\SearchRequest;

//... more code

$results = Model::search($query, function(SearchRequest $request) {
    $request->trackTotalHits(true);
    return $request;
})->paginate();

//... more code

Documentation and reference:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM