0

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

1 Answer 1

1

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
        ]
    ]
];
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.