FOSElasticaBundle – Only count the number of results for a query

Elasticsearch let you count results for a query without fetching its results (documents), which is faster. Here is how to do this very easily when using FOSElasticaBundle

Elasticsearch give multiple ways to only count the results of a query.

Either by requesting the following url /(index)/(type)/_count
Or by adding the “searchtype=count” query parameter to the usual url : /(index)/(type)/_search?search_type=count

La deuxième solution est recommandée par la doc, et ça tombe bien car c’est celle-ci que permet d’utiliser facilement Elastica et par extension, FOSElasticaBundle.

The second solution is the one recommended by the doc, and by chance it’s also the one Elastica (through FOSElasticaBundle) let you use very easily.

    $query = // whatever kind of Elastica Query
    $this->get('fos_elastica.index.yourindex.yourtype')->count($query); // return only the results count

As you notice, we didn’t used the “finder” provided by the bundle but directly the Elastica\Type class by using the following service : “fos_elastica.index.(index).(type)

A very short and simple post, but i hope might help someone not loosing too much time looking for the way to do this :)