elasticsearchelasticsearch-dsllaravel-scout

Filter on elasticsearch field if exists, otherwise ignore the filter


I'm trying to filter on two differents indice but in the same elastic query,

I would like to filter on a field that not exist on the two indices :

first indice :

label: string,
value: string,
isShowable: boolean

second indice :

label: string,
value: string

I want to retrieve all items from the second indice, and get only showable items from the first one.

I'm using Elasticsearch DSL in php.

Here is what I tried :

Item::search($formattedRequest, function (Client $client, Search $body) {
            $dispensationQuery = new TermQuery("isShowable", true);

            $bool = new BoolQuery();
            $bool->add($dispensationQuery, BoolQuery::SHOULD);

            $body->addQuery($bool);

            return $client->search(
                ['index' => firstIndex . "," . secondIndex, 'body' => $body->toArray()],
            );
        })->get();

But it filter on all my items and don't retrieve value from the second indice.

How to manage that ?


Solution

  • You can use a should clause to combine exists and bool check. It will be like return a document if either field exists or its value is true

    GET index1,index2/_search
    {
      "query": {
        "bool": {
          "should": [
            {
              "bool": {
                "must_not": [
                  {
                    "exists": {
                      "field": "isShowable"
                    }
                  }
                ]
              }
            },
            {
              "term": {
                "isShowable": {
                  "value": true
                }
              }
            }
          ]
        }
      }
    }