If you were to start a project in Grails with ElasticSearch, you would probably google a little bit and find that there is an existing ElasticSearch Grails’ Plugin which looks like the ideal tool to deal with this problem. Well, depending on the nature of your project it could be, or not, the best tool to use. Before you make your decision, I suggest you consider the elements I describe below.
When to use the ElasticSearch Grails’ plugin?
- Small projects (simple hierarchies, simple associations).
- One index per domain Class (given that having more than one means going for a manual management, it makes no sense to combine both an automatic and a custom approach)
- When you need simple mappings, and a generic approach.
- Simple Highlighting.
When NOT to use it?
- Complex domain projects (complex hierarchies, nested elements).
- Large projects.
- More than one index per class (like different views of the same class instance).
- Suggestions, custom Highlighting.
- Complex queries, based on decisions (like appending conditions based on parameters).
If you have assessed these issues and you find out that you should not use the plugin, but you feel that it will take you ages to start with a custom index management, don’t be afraid!
Building a custom index management solution
- Keep in mind that Elasticsearch is schema-free, so indexing is almost a piece of cake.
- Check the plugin code to get some ideas.
- Remember that most of the plugin is based on the SearchSourceBuilder.
- Use the Groovy client, which allows you to code using a simple approach.
- Use a good marshaller libraries like Jackson or Gson since sometimes custom index actions need domain transformation.
- Use multiple queries rather than deep instances (Queries are really fast in ES).
You can find below a couple of snippets to perform basic CRUD operations:
Create a search:
Just creating a SearchSourceBuilder instance, and setting all the needed sentences.
Execute the query:
Then we just need to use the builder instance to perform the query and get the response.
Remember that elasticsearch is schema-free, so unless you want to set something manually, ES takes care of index metadata.
As you’ve noticed, I used a custom wrapper class named ParamsWrapper that happened to be really useful to encapsulate the request params and adapt them to the Elasticsearch API syntax.
I hope you like it, please, let us know your comments to help us improve!