2016-09-17 95 views

回答

1

Laravel Scout不支持高級Elasticsearch功能。我最終堅持使用Scout來完成基於模型事件的所有索引創建和更新,但是我將搜索切換到直接使用ElasticSearch庫。

3

其實它可以簡單地與自定義偵察引擎完成。

我們稱之爲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() 
    { 
     // 
    } 
} 

不要忘記在配置/ app.php添加新的服務提供商:

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

,並更改驅動程序 「elasticquery」 在配置/ scout.php或.ENV(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(); 
+0

我喜歡這個解決方案,但現在,我只是通過ES PHP SDK直接查詢ElasticSearch。 – ATLChris