How to Implement Elasticsearch with rails
By: Shivani Nerkar Category: Ruby on Rails Technologies: Ruby on Rails
Elasticsearch is a powerful full-text search engine based on Apache Lucene. Elastic search is a search engine based on Apache Lucene — and information retrieval software library. It allows us to store, search and analyze big volumes of data in real-time.
Following are the steps of
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
12) Install Elasticsearch
Steps of Installation of elastic search:
- curl -fsSL https://artifacts.elastic.co/GPG-KEY-elasticsearch | sudo apt-key add -
- echo “deb https://artifacts.elastic.co/packages/7.x/apt stable main” | sudo tee -a /etc/apt/sources.list.d/elastic-7.x.list
- sudo apt update
- sudo apt install elasticsearch
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:
14) Add the search action in the post controller
15) Update the routes like below
16) Update the code of index.mhtl.erb under app/views/posts and add the following code.
17) rails s
Originally published at https://www.cryptextechnologies.com.