Search code examples
phpelasticsearchdslongr

ElasticsearchDSL builder how to create SHOULD NOT query


Using the php dsl builder, I'm trying to create a SHOULD NOT query. Using the json query syntax you can nest a MUST_NOT within a SHOULD bool to create one.

Example

{"bool": {"should": { "bool": {"must_not": {"match": {"thing": "thingy"}}}}}}

Reading through the ongr documentation it isn't clear how to achieve the same the result since the 5.0 update release. I've tried the following:

$search = new Search();
$query = new MatchQuery('thing', 'thingy');
$search->addQuery($query, BoolQuery::MUST_NOT);
$search->addPostFilter(BoolQuery::SHOULD);

but that doesn't work.


Solution

  • In order to nest the bool queries, you need to use bool queries :) The example you provided can be achieved with this code snippet:

    $search = new Search();
    $outerBoolQuery = new BoolQuery();
    $innerBoolQuery = new BoolQuery();
    $innerBoolQuery->add(new MatchQuery('thing', 'thingy'), BoolQuery::MUST_NOT);
    $outerBoolQuery->add($innerBoolQuery, BoolQuery::SHOULD);