2016-12-19 12 views
0

私はLaravelとElasticSearchでアプリケーションを作成しています。ElasticSearchとLaravelを使った動的検索

私は、さまざまなフィルタタイプ(ブランド、年、およびオプション)のフォームを持つ車両を見つけるための検索フィルタとして機能するページを持っています。

ユーザーは、フィールドのすべてまたは1つだけを入力できます。

$where = []; 

if($request->brand){ 
    $where[] = " `brand` => '{$request->brand}'"; 
} 
if($request->year) 
    { $where[] = " `cidade` => '{$request->year}'"; 
} 
if($request->item){ 
    $where[] = " `bairro` => '{$request->item}'"; 
} 

したがって、ユーザーが選択したフィールドを取得できます。

しかし、ユーザーが選択したフィールドのみを照会するための動的クエリの実行方法はわかりません。

ユーザーは、このように、すべてのフィールドを埋めた場合、私はのみ検索することができます。

$this->elasticParams['body'] = [ 
     'query' => [ 
      'bool' => [ 
       'should' => [ 
        ['match' => ['brand' => $request->brand]], 
        ['match' => ['year' => $request->year]], 
        ['match' => ['item' => $request->item]] 
       ] 
      ] 
     ] 
    ]; 

私は

答えて

1

私は知らないユーザーが記入したフィールドだけを追加したいと思いますElasticについては多くの場合、次のように'should'部分に条件付きで各フィールドを追加することができます。

$should = []; 

if ($request->brand) { 
    $should[] = ['match' => ['brand' => $request->brand]]; 
} 

if ($request->year) { 
    $should[] = ['match' => ['year' => $request->year]]; 
} 

if ($request->item) { 
    $should[] = ['match' => ['item' => $request->item]]; 
} 

// ... 

$this->elasticParams['body'] = [ 
    'query' => [ 
     'bool' => [ 
      'should' => $should 
     ] 
    ] 
]; 
関連する問題