Search code examples
phpsymfonyelasticsearchelasticafoselasticabundle

Get Elasticsearch Score in Symfony


Elasticsearch provides a score field if you do a get request via cURL.

{
  "_index": "twitter",
  "_type": "tweet",
  "_id": "123",
  "_score": 4.2,
  "firstName": "Max"
  "lastName": "Mustermann"
}

Is there a way to get this score inside symfony. I am wondering if FOSElasticaBundle provides a function similar to the one below to get the score.

$finder = $this->container->get('fos_elastica.finder.app.article');
$boolQuery = new \Elastica\Query\BoolQuery();

$fieldQuery = new \Elastica\Query\Match();
$fieldQuery->setFieldQuery('title', 'I am a title string');
$fieldQuery->setFieldParam('title', 'analyzer', 'my_analyzer');
$boolQuery->addShould($fieldQuery);

Solution

  • When searching with FOSElasticaBundle, you'll get a Elastica\ResultSet with Elastica\Result inside. You can iterate on those results, they have a getScore method to get what you need.

    $resultSet = $this->store->search($query);
    
    $results = $resultSet->getResults();
    
    foreach ($results as $result) {
        $score = $result->getScore();
    }
    

    Alternatively, you can get the score with this: $result->getParam('_score');