Elastica PHP Query Where Or

1.3k views Asked by At

How to make a WHERE categoryId = 1 OR categoryId = 2 query with Elastica ? I'm doing this but I got 0 result :

    $query = new \Elastica\Query();
    $boolOr = new \Elastica\Filter\BoolOr();
    $boolOr->addFilter(new \Elastica\Filter\Term(array('categoryId' => '1')));
    $boolOr->addFilter(new \Elastica\Filter\Term(array('categoryId' => '2')));
    $filtered = new \Elastica\Query\Filtered(new \Elastica\Query\MatchAll(), $boolOr);
    $query->setQuery($filtered);
    $products = $type->search($query)->getResults();
1

There are 1 answers

1
ruflin On

Here is a working example:

$index = $this->_createIndex();
$type = $index->getType('test');

$doc1 = new Document('', array('categoryId' => 1));
$doc2 = new Document('', array('categoryId' => 2));
$doc3 = new Document('', array('categoryId' => 3));

$type->addDocument($doc1);
$type->addDocument($doc2);
$type->addDocument($doc3);

$index->refresh();

$boolOr = new \Elastica\Filter\BoolOr();
$boolOr->addFilter(new \Elastica\Filter\Term(array('categoryId' => '1')));
$boolOr->addFilter(new \Elastica\Filter\Term(array('categoryId' => '2')));

$resultSet = $type->search($boolOr);

You don't need to use the filtered and matchall query. The working example can be found here: https://github.com/ruflin/Elastica/pull/887/files