如何使用Laravel Scout在ElasticSearch中设置track_total_hits?

x33g5p2x  于 2022-11-02  发布在  ElasticSearch
关注(0)|答案(2)|浏览(272)

我一直在使用https://github.com/babenkoivan/scout-elasticsearch-driver,我希望将“track_total_hits”设置为true,这样我就可以获得总结果。
https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-body.html#request-body-search-track-total-hits
我不知道如何将数组值设置为该点?

  • 谢谢-谢谢
lfapxunr

lfapxunr1#

您正在使用的软件包没有实现track_total_hits(搜索repo内容可以确认这一点)。但是,如果需要的话,您可以派生repo并自己添加功能。

jbose2ul

jbose2ul2#

我遇到了同样的问题,为了解决它,我创建了自己的实现,包括track_total_hits和更多......,使用回调闭包。

1.延长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;
    }
}
2.在AppServiceProvider中注册扩展的搜索请求工厂
public function register()
{
    $this->app->bind(SearchRequestFactoryInterface::class, ElasticSearchRequestFactory::class, true);
}
3.使用SearchRequest设置值
use ElasticAdapter\Search\SearchRequest;

//... more code

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

//... more code

文档和参考:

相关问题