Convert Figma logo to code with AI

elastic logoelasticsearch-rails

Elasticsearch integrations for ActiveModel/Record and Ruby on Rails

3,069
792
3,069
54

Top Related Projects

55,872

Ruby on Rails

Intelligent search made easy

5,648

Object-based searching.

pg_search builds ActiveRecord named scopes that take advantage of PostgreSQL’s full text search

Quick Overview

Elasticsearch-rails is a collection of Ruby gems that integrate Elasticsearch with Ruby on Rails applications. It provides tools for indexing ActiveRecord models, performing searches, and managing Elasticsearch indices within Rails projects.

Pros

  • Seamless integration with Ruby on Rails applications
  • Automatic indexing of ActiveRecord models
  • Flexible and customizable search functionality
  • Supports complex queries and aggregations

Cons

  • Learning curve for developers new to Elasticsearch
  • Can be resource-intensive for large datasets
  • Requires careful configuration for optimal performance
  • May introduce complexity in application architecture

Code Examples

  1. Basic model integration:
class Article < ApplicationRecord
  include Elasticsearch::Model
  include Elasticsearch::Model::Callbacks
end

This code adds Elasticsearch functionality to an ActiveRecord model, enabling automatic indexing and searching.

  1. Performing a simple search:
results = Article.search('ruby on rails')

This example performs a basic search for articles containing the phrase "ruby on rails".

  1. Custom search query:
results = Article.search(
  query: {
    multi_match: {
      query: 'elasticsearch',
      fields: ['title^5', 'content']
    }
  }
)

This code demonstrates a more complex search query, giving higher weight to matches in the title field.

Getting Started

  1. Add the gems to your Gemfile:
gem 'elasticsearch-model'
gem 'elasticsearch-rails'
  1. Run bundle install

  2. Include Elasticsearch modules in your model:

class Article < ApplicationRecord
  include Elasticsearch::Model
  include Elasticsearch::Model::Callbacks
end
  1. Index existing records:
Article.import
  1. Perform a search:
results = Article.search('your search query')

These steps will set up basic Elasticsearch integration for your Rails application, allowing you to index and search your models.

Competitor Comparisons

55,872

Ruby on Rails

Pros of Rails

  • Comprehensive full-stack web application framework
  • Large, active community with extensive documentation and resources
  • Built-in testing tools and conventions for rapid development

Cons of Rails

  • Steeper learning curve for beginners compared to Elasticsearch Rails
  • Can be overkill for smaller projects or simple search functionality
  • Performance may be slower for large-scale applications without optimization

Code Comparison

Rails (config/routes.rb):

Rails.application.routes.draw do
  resources :articles
  root 'home#index'
end

Elasticsearch Rails (app/models/article.rb):

class Article < ApplicationRecord
  include Elasticsearch::Model
  include Elasticsearch::Model::Callbacks
end

Summary

Rails is a full-featured web application framework, while Elasticsearch Rails is a specialized gem for integrating Elasticsearch with Rails applications. Rails offers a complete solution for building web applications, including routing, ORM, and testing tools. Elasticsearch Rails focuses on providing seamless integration between Rails and Elasticsearch for advanced search capabilities.

Rails is better suited for building complete web applications, while Elasticsearch Rails is ideal for adding powerful search functionality to existing Rails projects. The choice between the two depends on the specific requirements of your project and the level of search functionality needed.

Intelligent search made easy

Pros of Searchkick

  • Simpler and more intuitive API, making it easier for beginners to get started
  • Built-in support for faceted search, autocomplete, and highlighting
  • Automatic intelligent type casting and zero downtime reindexing

Cons of Searchkick

  • Less flexible for complex queries compared to Elasticsearch-Rails
  • May have performance limitations for very large datasets
  • Fewer configuration options for fine-tuning Elasticsearch behavior

Code Comparison

Searchkick:

class Product < ApplicationRecord
  searchkick
end

Product.search("apples", fields: [:name, :description])

Elasticsearch-Rails:

class Product < ApplicationRecord
  include Elasticsearch::Model
  include Elasticsearch::Model::Callbacks
end

Product.__elasticsearch__.search(
  query: { multi_match: { query: "apples", fields: ["name", "description"] } }
)

Searchkick provides a more concise and Ruby-like syntax, while Elasticsearch-Rails offers more granular control over query construction. Searchkick abstracts away much of the complexity, making it easier to use for simple cases, but potentially limiting for advanced use cases where fine-grained control is necessary.

5,648

Object-based searching.

Pros of Ransack

  • Simpler setup and integration with Rails applications
  • Works directly with ActiveRecord, no additional database required
  • Provides a powerful and flexible search form builder

Cons of Ransack

  • Limited to ActiveRecord-based searches, less suitable for large-scale text search
  • May become slower with complex queries on large datasets
  • Lacks advanced features like faceting and highlighting

Code Comparison

Ransack search:

@q = Person.ransack(params[:q])
@people = @q.result(distinct: true)

Elasticsearch-Rails search:

@people = Person.search(params[:q]).records

Key Differences

Ransack is primarily designed for creating complex search forms and queries within Rails applications using ActiveRecord. It's ideal for smaller to medium-sized datasets and provides a user-friendly interface for building advanced search functionality.

Elasticsearch-Rails, on the other hand, integrates Elasticsearch with Rails applications, offering powerful full-text search capabilities, scalability for large datasets, and advanced features like faceted search and relevance scoring.

Choose Ransack for simpler ActiveRecord-based searches and form building, while Elasticsearch-Rails is better suited for applications requiring robust, scalable full-text search functionality across large volumes of data.

pg_search builds ActiveRecord named scopes that take advantage of PostgreSQL’s full text search

Pros of pg_search

  • Native PostgreSQL integration, no additional infrastructure required
  • Simpler setup and configuration for basic search functionality
  • Lightweight and focused on PostgreSQL-specific features

Cons of pg_search

  • Limited to PostgreSQL databases only
  • Less advanced features compared to Elasticsearch for complex search scenarios
  • May not scale as well for extremely large datasets or high-volume search operations

Code Comparison

pg_search:

class Product < ApplicationRecord
  include PgSearch::Model
  pg_search_scope :search_by_name, against: :name
end

Product.search_by_name("example")

elasticsearch-rails:

class Product < ApplicationRecord
  include Elasticsearch::Model
  include Elasticsearch::Model::Callbacks

  settings index: { number_of_shards: 1 } do
    mappings dynamic: 'false' do
      indexes :name, analyzer: 'english'
    end
  end
end

Product.__elasticsearch__.search("example")

Both libraries offer search functionality, but pg_search is more straightforward for basic PostgreSQL-based searches, while elasticsearch-rails provides more advanced features and flexibility for complex search scenarios across various data sources.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Elasticsearch Rails

Ruby tests JRuby tests

This repository contains various Ruby and Rails integrations for Elasticsearch:

  • ActiveModel integration with adapters for ActiveRecord and Mongoid
  • Repository pattern based persistence layer for Ruby objects
  • Enumerable-based wrapper for search results
  • ActiveRecord::Relation-based wrapper for returning search results as records
  • Convenience model methods such as search, mapping, import, etc
  • Rake tasks for importing the data
  • Support for Kaminari and WillPaginate pagination
  • Integration with Rails' instrumentation framework
  • Templates for generating example Rails application

Elasticsearch client and Ruby API is provided by the elasticsearch-ruby project.

Installation

Install each library from Rubygems:

gem install elasticsearch-model
gem install elasticsearch-rails

Compatibility

The libraries are compatible with Ruby 3.0 and higher.

We follow Ruby’s own maintenance policy and officially support all currently maintained versions per Ruby Maintenance Branches.

The version numbers follow the Elasticsearch major versions. Currently the main branch is compatible with version 8.x of the Elasticsearch stack.

RubygemElasticsearch
0.1→1.x
2.x→2.x
5.x→5.x
6.x→6.x
7.x→7.x
8.x→8.x
main→8.x

Check out Elastic product end of life dates to learn which releases are still actively supported and tested.

Usage

This project is split into three separate gems:

Example of a basic integration into an ActiveRecord-based model:

require 'elasticsearch/model'

class Article < ActiveRecord::Base
  include Elasticsearch::Model
  include Elasticsearch::Model::Callbacks
end

# Index creation right at import time is not encouraged.
# Typically, you would call create_index! asynchronously (e.g. in a cron job)
# However, we are adding it here so that this usage example can run correctly.
Article.__elasticsearch__.create_index!
Article.import

@articles = Article.search('foobar').records

You can generate a simple Ruby on Rails application with a single command (see the other available templates). You'll need to have an Elasticsearch cluster running on your system before generating the app. The easiest way of getting this set up is by running it with Docker with this command:

  docker run \
    --name elasticsearch-rails-searchapp \
    --publish 9200:9200 \
    --env "discovery.type=single-node" \
    --env "cluster.name=elasticsearch-rails" \
    --env "cluster.routing.allocation.disk.threshold_enabled=false" \
    --rm \
    docker.elastic.co/elasticsearch/elasticsearch:7.6.0

Once Elasticsearch is running, you can generate the simple app with this command:

rails new searchapp --skip --skip-bundle --template https://raw.github.com/elasticsearch/elasticsearch-rails/main/elasticsearch-rails/lib/rails/templates/01-basic.rb

Example of using Elasticsearch as a repository for a Ruby domain object:

class Article
  attr_accessor :title
end

require 'elasticsearch/persistence'
repository = Elasticsearch::Persistence::Repository.new

repository.save Article.new(title: 'Test')
# POST http://localhost:9200/repository/article
# => {"_index"=>"repository", "_id"=>"Ak75E0U9Q96T5Y999_39NA", ...}

Please refer to each library documentation for detailed information and examples.

Model

Persistence

Rails

Development

To work on the code, clone the repository and install all dependencies first:

git clone https://github.com/elastic/elasticsearch-rails.git
cd elasticsearch-rails/
bundle install
rake bundle:install

Running the Test Suite

You can run unit and integration tests for each sub-project by running the respective Rake tasks in their folders.

You can also unit, integration, or both tests for all sub-projects from the top-level directory:

rake test:all

The test suite expects an Elasticsearch cluster running on port 9250, and will delete all the data.

License

This software is licensed under the Apache 2 license, quoted below.

Licensed to Elasticsearch B.V. under one or more contributor
license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright
ownership. Elasticsearch B.V. licenses this file to you under
the Apache License, Version 2.0 (the "License"); you may
not use this file except in compliance with the License.
You may obtain a copy of the License at

	http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.