ElasticSearch with Ruby on Rails: how to code faster
The benefits of using ElasticSearch with Ruby on Rails are too numerous to fit into a meta description. Find out what they are!

Editorial translation by Impulso.
Picking up new skills and learning programming languages opens up more opportunities for developers looking for a job and for independent professionals alike. It’s also worth getting to know the main frameworks for those languages and the tools that go with them. That goes for ElasticSearch with Ruby on Rails, too!
That way, you can speed up software development and simplify your day-to-day work. Ruby, for example, ranks among the ten most popular programming languages, with around 1.5 million developers.
That’s according to the 19th edition of SlashData’s “State of the Developer Nation” study. The survey covered more than 17,000 developers in 159 countries in the third quarter of 2020.
Ruby is therefore one of the most popular languages on the market and is used in app development, IoT, cloud computing, and more. Ruby on Rails is one of the most popular frameworks for the language, while ElasticSearch is a search engine.
Next, we’ll take a closer look at how the two work and why they might be useful to you. Read on to see what we’ve put together!
- What is Ruby?
- What is Ruby on Rails?
- Benefits of Ruby on Rails
- Recommended use cases for Ruby on Rails
- What is ElasticSearch?
- What is ElasticSearch used for?
- Gems
- Searchkick
- Aggregations
- What to watch out for with ElasticSearch
- ElasticSearch concepts
- The importance of a fast, efficient search system
- The benefits of working with ElasticSearch and Ruby on Rails
What is Ruby?

Ruby is a programming language developed by Yukihiro “Matz” Matsumoto in Japan in 1995. Programs written in Ruby use the Model-View-Controller (MVC) pattern. Here are some more of Ruby’s features:
- object-oriented;
- strongly and dynamically typed;
- an interpreted, multi-paradigm language that supports reflective, functional, imperative, and object-oriented programming;
- automatic memory management;
- methods for creating code on the fly, in real time;
- variables are objects;
- uses Code Blocks. Blocks add flexibility because you can pass a closure to any method to describe how it should behave. The closure is called a block;
- blocks are inspired by functional languages;
- Ruby supports only single inheritance. It does, however, have modules, which are collections of methods;
- that brings us to mixins. In other words, they let you add methods to a class without inheriting from another class. A class can use a module as a mixin to get all the module’s methods directly;
- all types are classes, so there are no “primitive types”;
- no variable declarations are needed. Ruby uses simple naming conventions to indicate variable scope;
- available on Linux, Windows, Mac OS X, and other platforms.
It’s worth noting that Ruby’s creator combined “bits” of his favorite languages, including Smalltalk, Perl, Python, Eiffel, Ada, and Lisp.
One of his goals was for Ruby to be more object-oriented than Python. He also wanted a scripting language with better performance than Perl.
What is Ruby on Rails?

Ruby on Rails, also known as RoR or Rails, is essentially a cross-platform, open-source framework written in Ruby and released in 2004.
Its purpose is to make it easier and faster to build database-driven websites. It does this by letting you build applications using predefined structures.
Benefits of Ruby on Rails

In some ways, RoR is simple to use. It’s also dynamic and straightforward, making it quick and easy to build web applications.
It’s also worth mentioning that it comes with many libraries of reusable code known as gems (we’ll take a closer look at those later). You can activate them quickly with a single command.
This makes things easier during development, freeing up time for other activities. The framework also continues to improve in line with software development best practices.
One example is “Don’t Repeat Yourself”, the principle of avoiding code duplication. Another is the use of unit tests. A standard folder structure is also encouraged in projects.
Another plus is the range of market opportunities, since many companies use Ruby or have used it in the past. They include some well-known names, such as Airbnb, Hulu, and Twitter.
Recommended use cases for Ruby on Rails

As the SlashData survey points out, Ruby has been more popular in the Internet of Things (IoT), cloud computing, and app development. But Ruby can be used in other areas, and so can RoR.
Ruby has a wide range of uses, including building desktop applications and working with embedded systems. RoR, for its part, made it much easier to build web applications.
What is ElasticSearch?

At its core, ElasticSearch is a distributed full-text search tool. Here are some of its features:
- engine based on the Lucene library;
- multitenancy support;
- HTTP web interface;
- schemaless JSON documents.
Specifically, the official website describes it as a data analysis tool. It is also a distributed RESTful search engine.
ElasticSearch can handle a growing number of use cases. It is also a core component of the Elastic Stack, a suite of open-source software.
This suite was designed and built to help users find sources of all kinds, in any format. It is also used to search, visualize, and analyze the data collected, all in real time.
ElasticSearch stores data centrally. This enables fast, analytical searches that can be scaled up fairly easily. The tool also aims to provide fine-tuned relevance.
What ElasticSearch is used for

Basically, ElasticSearch is used to run quick, focused searches. This makes it possible to generate reports, dashboards, and general statistics, as well as store logs for later review. Its speed and precision make ElasticSearch a good fit for systems with high data throughput.
Why use ElasticSearch

There are several reasons to use this solution, including the fact that it is open source. It also has a large community. On GitHub alone, users have already given its repository nearly 55,000 stars.
The tool’s speed is another feature that sets it apart. To achieve it, ElasticSearch uses the Apache Lucene API. It performs lookups using an inverted index. The way these indexes are stored makes it easier for ElasticSearch to retrieve the information you’re looking for.
Its architecture is also distributed and scalable by default. So if you want to scale your application or search service, you can run ElasticSearch on as many servers as you like, and it will handle that well.
ElasticSearch is designed for full- text search, meaning searches across the full text. It quickly finds occurrences of a word or term in a table without having to scan its rows. You also don’t need to know which column the term is stored in.
Full- text search works by using text indexes. You can see this feature in action when you type something into Google. The search engine starts showing you some results ahead of time. That’s basically full- text search in action.
Another advantage is that you can run complex queries. Also, when you save information to an index, it takes ElasticSearch at least a few milliseconds to make it searchable.
Gems

Gems are libraries of reusable Ruby code. They’re managed by RubyGems, a package distribution system that makes gems easier to develop, install, and share. ElasticSearch has several gems, including:
- elasticsearch-ruby (official);
- elasticsearch-rails (official);
- chewy;
- searchkick.
The first two are official gems from ElasticSearch itself. You can use them to create and customize query interfaces however you like.
Searchkick

Searchkick deserves a special mention because it does, so to speak, Active Record’s “job” for ElasticSearch in Ruby on Rails. It also makes indexing very simple.
After installing this gem, add the line “searchkick” to the model where you want to use ElasticSearch. Once you do that, the integration is complete and your indexes _(_models that will become indexes) will be updated automatically.
You can also do this manually. By default, every column in a model is indexed. It’s worth noting that searches are easy to run with Searchkick. Other features of this gem include:
- the syntax is similar to Active Record’s;
- pagination is integrated with ElasticSearch;
- it supports the ElasticSearch DSL;
- when running a full-text search, you can add a specific query (inside the “where” field), limit results, boost a field you want to give more weight to, and so on.
Aggregations
One interesting feature is the use of aggregations, which provide aggregated search data. For example, for a list of products, aggregations would give you the number of products in each category.
In a conventional architecture, you’d need to run several queries at once to load and display this information. With ElasticSearch, you only need to run one query and set (assign values for) as many “aggregations” as you like by type, such as sums and averages.
If you want autocomplete based on the first few letters of a field, you can use a searchkick option to specify where to match the text: the whole word (word), the middle of the word (word_middle), the end of the word (word_end), and so on.
For example, you can add autocomplete for products based on the beginning of each word (word_start)in a table column that identifies those products, such as one called “name”.
After this process, known in ElasticSearch as “mapping,” the system will find the mapping and suggest results based on the first words in the “name” field (column).
This lets you give certain fields more weight so users get faster searches and more accurate autocomplete suggestions.
In short, searchkick is a full-featured tool that lets you run several types of searches. That can help you retrieve higher-quality data. It also simplifies development.
What to watch out for with ElasticSearch
You can replace Active Record searches with ElasticSearch searches because the way you run them is very similar. Still, it’s important to consider the infrastructure and how the system will run in production.
That’s because running an ElasticSearch server or maintaining instances comes at a cost. Available services usually charge by the number of shards, which are basically subdivisions of your indexes.
So we don’t recommend adding searchkick “everywhere” by putting it in all your models in the project. After all, you’ll need ElasticSearch infrastructure that can handle the load. And that costs money.
You can decide where to use the tool. In other words, identify the specific parts of your system that need fast searches and quick results.
For example, say you need to check during checkout whether a customer has an unused coupon they can apply right then. You can use ElasticSearch to get the answer in milliseconds.
In short, the tip is to use ElasticSearch only in the models where it makes sense, instead of adding it to all of them. That could save you money.
ElasticSearch concepts

To get a better understanding of this search tool, it helps to get familiar with a few concepts and terms first. We’ve put together a short list of some of the terms you’ll see most often. We’ve already mentioned a few of them, but they’re worth revisiting. Take a look! 😉
Cluster and nodes
If you want to increase capacity, you can add nodes, which are the servers, to a cluster. ElasticSearch will automatically distribute the data and the query load across the available nodes.
You don’t need to make changes to your app because Elasticsearch knows how to balance clusters across multiple nodes to provide availability and scale.
For better performance, the nodes in a cluster need to be on the same network. Balancing shards in a cluster across nodes in separate data centers takes longer.
Another feature worth highlighting is Cross-Cluster Replication (CCR), or replication between clusters. This feature lets you sync indexes from the primary cluster to a remote secondary cluster that serves as a live backup.
This happens automatically, so the secondary cluster can take over from the primary if it runs into problems.
Index
An Elasticsearch index is a logical grouping of one or more physical shards, where each shard is a self-contained index.
To ensure redundancy, ElasticSearch distributes the documents in an index across several shards and distributes those shards across multiple nodes. Redundancy protects against hardware failures.
Query capacity also grows as you add nodes to a cluster. Another point worth noting is that as the cluster changes size, the shards are automatically moved to rebalance the cluster.
Shard
A shard, meaning something like “fragment,” is a unit Elasticsearch uses to distribute data across the cluster. Basically, a shard is an instance of an Apache Lucene index, one of the “parts” the instance is divided into.
When you create an index, five shards are created by default. These are Lucene indexes where documents are indexed and searched.
After an error, how quickly ElasticSearch can move shards to rebalance the data depends on the number of shards, their size, and disk and network performance.
ElasticSearch distributes documents across shards using a hash that it computes for each document. Based on that hash, it sends the document to one of the shards.
An important precaution is to avoid having too many shards. In ElasticSearch, the number of shards on a node is proportional to the available heap space. Generally, you should have fewer than 20 shards per GB of heap space.
Replica
ElasticSearch lets you copy the shards in your index into what are known as “replica shards ” (or simply replicas). In addition to the original shard, an index can have zero or more replicas.
So there are two types of shards: replicas and primaries. Each document in an index belongs to a shard of the primary type. A replica is simply a copy of a primary shard.
Replicas provide redundant copies of your data. This helps protect against hardware failures and increases the system’s capacity to handle read requests, such as searches.
The number of primary shards in an index is set when the index is created. Likewise, the number of replica shards can be set for each index when you create it.
You can change the number of replicas at any time without interrupting queries or indexing.
Why a fast, efficient search system matters

One reason the advantage of using ElasticSearch with Ruby on Rails stands out is today’s need for fast, dynamic search systems.
In this case, that feature has become a requirement for anyone who wants to give users a positive browsing experience, keep them satisfied, and encourage them to spend more time using a web solution.
At a time when a delay of just a few seconds can make someone give up on a program, website, or app, a tool like ElasticSearch can set it apart.
Results also need to be high quality so they don’t frustrate the people searching. In enterprise solutions, returning results quickly is essential for company teams to find the data they need.
That way, teams can work faster while improving their time management. The same goes for the IT team.
The benefits of using ElasticSearch with Ruby on Rails

Generally speaking, we can say that developers who use ElasticSearch with Ruby on Rails can write code faster.
As a result, they can boost productivity. And it’s straightforward, since this framework offers plenty of easy-to-use features.
Another point worth highlighting is that ElasticSearch’s fast search, especially with searchkick, makes things quicker and more satisfying for anyone who needs to use the tool, particularly end users.
Because results appear almost instantly, this tends to save time and make it quicker to find essential data for day-to-day work, both in the IT department and across the rest of the company.
It’s worth noting that even when words have the wrong accents or terms are split incorrectly, the system tends to find relevant results. What’s more, the flexibility of this solution lets you tune search performance and improve a range of datasets. The same applies to use cases.
Finally, using ElasticSearch with Ruby on Rails can help anyone looking to add fast, dynamic search to their web application, especially if they write code in Ruby. That way, they can make improvements to their work more quickly.
Did you enjoy learning how ElasticSearch with Ruby on Rails can help you implement an advanced search tool? If you work with React in JavaScript, find out how to handle forms with Formcat, or check out Impulso Talks: Ruby on Rails below to learn about techniques covering architecture, product, MVPs, and more! 🎬


