Symfony2: elasticsearch custom repositories

This is the fourth in a series of posts about using elasticsearch with Symfony2:

  1. Symfony2: Integrating elasticsearch</a
  2. Symfony2: improving elasticsearch results</a
  3. Symfony2: elasticsearch custom analyzers
  4. Symfony2: elasticsearch custom repositories

A new feature of the FOQElasticaSearch bundle is the provision of repositories similar to those for Doctrine queries. The first advantage of this is that instead of having to use the finder service specific to a particular entity you can use the same manager service for all mapped entities and use the entity class name to get a repository to run queries against. So using the query we have built up in the previous posts:

Note that the use of the short syntax ExampleBundle:Site is only available in master, if you are using the branch compatible with 2.0.x Symfony releases then you will need to use the fully qualified class name e.g. LimeThinkingExampleBundleEntitySite.

A much bigger advantage of using this functionality is that we can create a custom repository to encapsulate our query which will clean up our controller method and make it easy to reuse elsewhere. So our custom repository looks like this:

The custom repository must extend the base repository in order to be able to use the relevant finder service, which is automatically injected in. We also need to specify the custom repository class. In master this can be done using an annotation:

For the 2.0 branch we need to specify it in our config, which now looks like this:

Our controller method can now be simplified to this:

The controller method is now much cleaner with the implementation of the query moved to the repository, the query can now also easily be reused elsewhere.