Mayor of the Plattenbaus
Mayor of the Plattenbaus

Reputation: 1256

How to add a filter to a result set?

I am using FOSElasticaBundle and Symfony. I have a method to return some results merged from two types of objects:

public function getMergedResults($query)
{
    //See https://github.com/FriendsOfSymfony/FOSElasticaBundle/blob/master/doc/cookbook/multi-type-search.md

    $indexManager = $this->get('fos_elastica.index_manager');
    $transformer = $this->get('app.elastica_to_model.transformer.snapshot');

    /* @var \Elastica\Search $search */
    $search = $indexManager->getIndex('app')->createSearch();
    $search->addType('snapshot');
    $search->addType('traffic_company');

    $search->setQuery($query);

    $resultSet = $search->search();

    $transformer = $this->get('fos_elastica.elastica_to_model_transformer.collection.app');

    $resultSet = $transformer->transform($resultSet->getResults());

    return $resultSet;

}

... which works well. Now I want to add a filter that was left to me by a previous developer:

protected function addSiteFilter(Query\BoolQuery $boolFilter, SiteInterface $site = null)
{
    if ($site) {
        $termFilter = new Query\Term(array('site' => array('value' => $site->getId())));

        $boolFilter->addMust(array(
            $termFilter
        ));
    }
}

... but I'm not sure how to glue these two pieces together. What code can I add to the first function so that it integrates the second one?

Upvotes: 0

Views: 141

Answers (1)

Lukas Zmoginas
Lukas Zmoginas

Reputation: 86

I'll provide an example, If it wouldn't be so clear for you, ping me.

/**
 * @param string $ownerId
 * @return Query
 */
public function getByOwnerId(string $ownerId): Query
{
    $terms = new Terms('ownerId', [$ownerId]);
    $boolQuery = (new BoolQuery())->addMust($terms);

    return (new Query())->setQuery($boolQuery);
}

Upvotes: 0

Related Questions