Search code examples
symfonyelasticsearchelasticafoselasticabundle

Foselasticabundle : How to add a script to FunctionScore in a query ? Elastica


I need to add a functionScore to my query to define a specific relevance for my results.

Here is my working code :

 $query      = new BoolQuery();
 $filters    = new BoolFilter();

 $query = new Query\Term();

 $query->setTerm($field, $value);
 $query->addMust($query);
 $query = new Query\Filtered($query, $filters);

 $finalQuery = new Query($query);
 $finalQuery->addSort(array('maxCapacity' => array('order' => 'asc')));

 $type->search($finalQuery, array('from' => (int)$from, 'size' => (int)$limit));

And I need to add something like this to my query, but I can't figure out how to do :

 $script = new Script("doc['pricehour'].value * 0.2 + doc['priceDay'].value * 0.4");
 $score = new \Elastica\Query\FunctionScore();
 $score->addScriptScoreFunction($script);

Am I in the right direction?

P.S. My _score in the result set is null since I used the sort, any idea on how to reactivated it with FosElasticaBundle?


Solution

  • Solution moved from @GregOs's question post.

    I finally found the solution. Everything in Elastica is about wrapping the queries.

    I now can perform a FunctionScore query like this :

    $scoreQuery = new Query\FunctionScore($query);
    $finalQuery = new Query($scoreQuery);
    
    $script = new Script("doc['pricehour'].value * 0.2 + doc> ['priceDay'].value * 0.4");
    $scoreQuery->addScriptScoreFunction($script);
    
    $type->search($finalQuery, array('from' => (int)$from, 'size' => (int)$limit));
    
    And I perform either the score, either the sort.