How to Implement Elasticsearch with rails

How to Implement Elasticsearch with rails

17 Sep 2022
0 Comments
How to Implement Elasticsearch with rails

What is Elasticsearch?

Elasticsearch is a powerful full-text search engine based on Apache Lucene. Elastic search is a search engine based on Apache Lucene — and an information retrieval software library. It allows us to store, search and analyze big volumes of data in real-time.
 

Full-text search engine: A search engine examines all of the words in every stored document as it tries to match search criteria.

Apache Lucene: It is a search engine library written entirely in java.


Following are the steps

1) rails new elastic_search_app

2) cd elastic_search_app

3) bundle

4) rails db:create db:migrate db:seed

5) rails assets:precompile

6) Performed the CRUD for Post Model.

  • rails g controller posts index create new update destroy
  • rails g model post author:string title:string body:test published:boolean published_on:timestamp

7) rails db:migrate

8) set routes

  • resources:posts
  • root ‘posts#index’

9) rails s

10) In the gem file add the below line of code

  • gem ‘elasticsearch-model’
  • gem ‘elasticsearch-rails’

11) Add the below code in the post.rd file
elasticsearch-code


12) Install Elasticsearch
Steps of Installation of elastic search:


Configure elastic search:

  • sudo nano /etc/elasticsearch/elasticsearch.yml
  • set network.host: localhost
  • sudo systemctl start elasticsearch
  • sudo systemctl enable elasticsearch


Securing elastic search:

  • sudo ufw allow from 198.51.100.0 to any port 9200
  • sudo ufw enable
  • sudo ufw status


Testing elastic search:

  • curl -X GET ‘http://localhost:9200'

13) We are going to create a class method in the post model that will take the search query as an argument but it will fetch only published posts. Add the following method in the app/models/post.rb file:
elastic-search-create

14) Add the search action in the post controller

elastic-search-action

15) Update the routes like below
elastic-search-routes

16) Update the code of index.mhtl.erb under app/views/posts and add the following code.
elastic-search-index

17) rails s




Leave a comment: