pan_slaw
pan_slaw

Reputation: 31

elasticsearch - where fields is null

I'm trying to write query (with foselastica bundle) where value should be some id or can be null.

In mysql: WHERE city.id = 1 OR city.id IS NULL

I know that I should use exists and must not expression, but not working for me. Any advice?

    $query = new \Elastica\Query();

    if ($phrase) {
        $queryString = new \Elastica\Query\QueryString($phrase);
        $query->setQuery($queryString);
    }

    $filter = new \Elastica\Query\BoolQuery();

    $city = new \Elastica\Query\Match();
    $city->setFieldQuery('city.id', $cityId);
    $filter->addShould($city);

    $nullCity = new \Elastica\Query\Exists('city.id');
    $filter->addMustNot($nullCity);

    $query->setPostFilter($filter);

Upvotes: 3

Views: 1850

Answers (1)

Elyass
Elyass

Reputation: 726

You're close to it. Try something like

$query = new \Elastica\BoolQuery();
// ...
$filter = new \Elastica\Query\BoolQuery();

$city = new \Elastica\Query\Match();
$city->setFieldQuery('city.id', $cityId);
$filter->addShould($city);

$nullCity = new BoolQuery();
$existQuery = new \Elastica\Query\Exists('city.id');
$nullCity->addMustNot($existQuery);
$filter->addShould($nullCity);

$query->addMust($filter); 

Upvotes: 5

Related Questions