我正在与Laravel Scout和Elasticsearch构建搜索集成。我试图找出如何改进我的查询以进行提升。
是否可以使用Laravel Scout执行此操作,还是需要直接恢复使用ElasticSearch PHP库?
答案 0 :(得分:4)
实际上可以使用自定义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();
答案 1 :(得分:2)
Laravel Scout不支持高级Elasticsearch功能。我最终坚持使用Scout来完成基于模型事件的所有索引创建和更新,但我将搜索切换为直接使用ElasticSearch库。