我正在与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中将驱动程序更改为“elasticquery”(SCOUT_DRIVER = 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/