Software engineer, data guy, Open Source enthusiast, New Hampshire resident, husband, father. Fan of guitars, hiking, photography, homebrewing, sarcasm.
Elasticsearch autocomplete with a Rails API backend and an Angular frontend
In this post, I’ll share some sample code to integrate a Rails backend API with Elasticsearch and an Angular frontend to implement autocomplete functionality.
To install Elasticsearch, I simply use brew:
Part 1: the Rails backend
Initial project setup:
Add Ruby gems, edit file: Gemfile, add:
Execute bundle install to install the gems.
Edit file ‘config/application.rb’ to enable elasticsearch logging, add:
Create a migration to add the table for People, new file: ‘db/migrate/20160929000649_create_people.rb’
Execute the migration and create the table via: rake db:migrate.
At this point, you can force create the elasticsearch index mapping for the person model:
The elasticsearch index mapping can be confirmed via: curl http://localhost:9200/es_demo_people/_mapping | python -m json.tool
Now we can create some data. To keep it simple I used Sidekiq. Here is a simple worker file: app/workers/person_creator_worker.rb
And a rake task to create People from a *nix system dict file using sidekiq. new file: lib/tasks/import.rake
Import the data via sidekiq and the new rake task. The import time can vary depending on how many workers and CPUs you use.
Now that we have data in elasticsearch, we can make it accessible to the front-end via a new controller. The controller has one GET route that uses the “q” query string param for user input. new file: app/controllers/api/people_controller.rb
Add the controller GET route, edit file: config/routes.rb
Add a basic CORS configuration, edit file: config/initializers/cors.rb
This concludes the Rails API backend, start the webserver via: rails s
For the Angular frontend, I chose to scaffold my project using the Yeoman Angular Gulp generator. By default, the generator adds sample content, modules, services, controllers, etc. I used the file structure as a guide and then deleted all the NPM packages and code that I didn’t want.
The first file I created was a new autocomplete service to call the Rails API backend. new file: src/app/components/autocomplete/autocomplete.service.js
Next I added the autocomplete directive. It injects the autocomplete service as a dependency, specifies which html template to use, and implements the controller functionality. new file: src/app/components/autocomplete/autocomplete.directive.js
Here is the basic autocomplete HTML template I used for the markup. new file: src/app/components/autocomplete/autocomplete.html
I then revised the main HTML file to include the new directive, edit file: src/app/main/main.html
Start the Angular frontend server via: gulp serve.
Here is a GIF showing all the components working together: