Reputation: 35
I'm creating an application with Laravel and ElasticSearch.
I have a page that acts as a search filter to find vehicles with a form with various filter types (brand, year, and optional).
The user can fill in all or just one of the fields.
$where = [];
if( $request->brand ){
$where[] = " `brand` => '{$request->brand}'";
}
if( $request->year )
{ $where[] = " `cidade` => '{$request->year}'";
}
if( $request->item ){
$where[] = " `bairro` => '{$request->item}'";
}
So I can get the fields that have been chosen by the user.
But I do not know how to do a dynamic query to query only the fields chosen by the user.
I can only search if the user fills in all the fields, like this:
$this->elasticParams['body'] = [
'query' => [
'bool' => [
'should' => [
['match' => ['brand' => $request->brand]],
['match' => ['year' => $request->year]],
['match' => ['item' => $request->item]]
]
]
]
];
I would like to add only the fields that the user has filled out
Upvotes: 0
Views: 555
Reputation: 16333
I don't know much about Elastic, but you should be able to conditionally add each field to the 'should'
part like this:
$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
]
]
];
Upvotes: 1