Filtering based on whether array passed into search query is empty

Hi. I would like to perform a search query based on passing in an array of values to the search function in php. This array may or may not be an empty array. I would like to set the filter in such a way that it compares each element in the array against the chosen parameter, but allows everything to pass if an empty array is passed in. Currently what i have here is searching for an empty string in the chosen parameter, which therefore returns me no results (since I have no items will color = null). May I know how this can be done?

    $a = array('');

$query = $client->search([
    'index' => 'fruits',
    'type' => 'fruit',
    'from' => 0, 'size' => 9999,
    'body' => [
        'query' => [
            'bool' => [
                'should' => [
                    ['match' => ['color' => ['query' => $q, 'boost' => 3]]],
                    ['match' => ['name' => ['query' => $q, 'boost' => 0.5]]],
                ],
                'filter' => [
                    ['terms' => ['color' => $a]]
                ]
                ]
                ],
                ]]
]);

There may be a clever way to do this in Elasticsearch (I haven't thought about it very much), but honestly this is something best done in your application.

E.g. if the array is non-empty, add the filter:

$query = [
    'index' => 'fruits',
    'type' => 'fruit',
    'from' => 0, 'size' => 9999,
    'body' => [
        'query' => [
            'bool' => [
                'should' => [
                    ['match' => ['color' => ['query' => $q, 'boost' => 3]]],
                    ['match' => ['name' => ['query' => $q, 'boost' => 0.5]]],
                ],
                'filter' => []
                ]
                ],
                ]]
]);

if (count($a) > 0) {
  $query['body']['bool']['filter'][] =  ['terms' => ['color' => $a]];
}

$response = = $client->search($query);

thanks, Zachary!

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.