gpt4 book ai didi

laravel - 如何使用 Laravel Scout 和 ElasticSearch 设置提升和过滤器?

转载 作者:行者123 更新时间:2023-11-29 02:49:34 24 4
gpt4 key购买 nike

我正在构建与 Laravel Scout 和 Elasticsearch 的搜索集成。我正在尝试弄清楚如何改进我的提升查询。

是否可以使用 Laravel Scout 执行此操作,或者我是否需要恢复为直接使用 ElasticSearch PHP 库?

最佳答案

实际上,它可以通过自定义 Scout Engine 轻松完成。

例如,我们称它为 ElasticqueryEngine,并从默认的 ElasticsearchEngine 扩展它:

<?php

namespace App\Libs\Scout\Engines;

use Laravel\Scout\Builder;
use Laravel\Scout\Engines\ElasticsearchEngine;

class ElasticqueryEngine extends ElasticsearchEngine
{
/**
* Perform the given search on the engine.
*
* @param Builder $query
* @param array $options
* @return mixed
*/
protected function performSearch(Builder $query, array $options = [])
{
if (!is_array($query->query)) {
return parent::performSearch($query, $options);
}

$searchQuery = [
'index' => $this->index,
'type' => $query->model->searchableAs(),
'body' => [
'query' => $query->query,
],
];

if (array_key_exists('size', $options)) {
$searchQuery = array_merge($searchQuery, [
'size' => $options['size'],
]);
}
if (array_key_exists('from', $options)) {
$searchQuery = array_merge($searchQuery, [
'from' => $options['from'],
]);
}
return $this->elasticsearch->search($searchQuery);
}
}

添加新的服务提供商以注册新的 ElasticqueryEngine(或在任何现有服务提供商中注册):

<?php

namespace App\Providers;

use Laravel\Scout\EngineManager;
use Illuminate\Support\ServiceProvider;
use Elasticsearch\ClientBuilder as Elasticsearch;
use App\Libs\Scout\Engines\ElasticqueryEngine;

class ElasticqueryServiceProvider extends ServiceProvider
{
/**
* Perform post-registration booting of services.
*
* @return void
*/
public function boot()
{
resolve(EngineManager::class)->extend('elasticquery', function () {
return new ElasticqueryEngine(
Elasticsearch::fromConfig(config('scout.elasticsearch.config')),
config('scout.elasticsearch.index')
);
});
}

/**
* Register bindings in the container.
*
* @return void
*/
public function register()
{
//
}
}

不要忘记在 config/app.php 中添加新的服务提供者:

'providers' => [
// ...
Laravel\Scout\ScoutServiceProvider::class,
App\Providers\ElasticqueryServiceProvider::class,
],

并在 config/scout.php 或 .env (SCOUT_DRIVER=elasticquery) 中将驱动更改为“elasticquery”

毕竟,您可以通过 https://www.elastic.co/guide/en/elasticsearch/reference/current/full-text-queries.html 中的任何查询进行搜索:

$query = [
'simple_query_string' => [
'query' => 'findme',
'fields' => [
'title^5',
'description',
],
],
];
$posts = Posts::search($query)->get();

// also you can use default ElasticsearchEngine query
$posts = Posts::search('findme')->where('user_id', 1)->get();

关于laravel - 如何使用 Laravel Scout 和 ElasticSearch 设置提升和过滤器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39541603/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com