Elasticsearch + Craft makes for a more flexible search experience.
For one of our clients, we recently swapped out the default CraftCMS search functionality. We chose to do this because our site needed more flexibility. In particular different types of content needed to be emphasized in different ways, and the default craft search just was not configurable enough. I ended up writing a custom plugin to replace the search functionality, as we would like to have this plugin evolve separately from the site that is using it. I replaced the search functionality entirely by updating the search component in config/app.php.
Here are some lessons learned about replacing the search functionality with elasticsearch:
- When you replace the search functionality, you replace it everywhere, including in the control panel. If there are any sections you don’t want to index in elasticsearch, you can leverage the default search. I wasn’t able to find an elegant way to do that, so the plugin just looks for the first element passed to it, and if that element is from a section where I want to defer to the default sql based search, I call into that component (which is registered under a different name).
- The search filtering in the Search service filters a list of element ids and all the results expect back are element ids. This means that you need to make sure you add the elementId to your index, and that is the only item you need to return. (Which makes the elasticsearch query much quicker than returning everything.)
- You can easily re-index on entry change, but it is simpler to just do a re-index of everything every so often. Depending on how often you need your search results refreshed, you may be able to get by with the simpler option.
- Hosted elasticsearch makes a ton of sense. We evaluated a couple of solutions but went with Elastic.co hosted search, which had good pricing, an intuitive interface and default SSL + basic auth.
Here are some lessons learned about craft plugins in general:
- Get the plugin to work first, then extract configuration. Craft makes it very easy to pull settings out into a model, and you should absolutely do that, but focus on getting things working first.
- Use the plugin generator to avoid writing boilerplate.
- When working on a plugin, it’s easier to just edit php files directly in the vendor directory, then once they work, copy them over to the plugin repository and cut a full fledged release.
- It’s really easy to swap out entire components.
- If your plugin is in a private git repository, make sure you understand how to let composer access it.
All in all, the flexibility gained was worth the extra work.