Add the
elasticsearch
andelasticsearch-model
gems: Add these to yourGemfile
:rubygem 'elasticsearch-model' gem 'elasticsearch-rails'
Then run:
shbundle install
Step 3: Configure Elasticsearch in Rails
Create an Elasticsearch Configuration File: Create a file named
config/elasticsearch.yml
with the following content:yamldevelopment: url: http://localhost:9200 test: url: http://localhost:9200 production: url: <your-production-elasticsearch-url>
Create an Initializer: Create an initializer file
config/initializers/elasticsearch.rb
:rubyElasticsearch::Model.client = Elasticsearch::Client.new host: ENV['ELASTICSEARCH_URL'] || 'localhost:9200'
Step 4: Integrate Elasticsearch with Your Models
Include Elasticsearch in Your Model: Let's say you have a
Post
model. Include Elasticsearch and its necessary modules:rubyclass Post < ApplicationRecord include Elasticsearch::Model include Elasticsearch::Model::Callbacks end
Customize Your Elasticsearch Index: You can customize how your model is indexed. Add an index definition to your model:
rubyclass Post < ApplicationRecord include Elasticsearch::Model include Elasticsearch::Model::Callbacks settings do mappings dynamic: false do indexes :title, type: :text, analyzer: 'english' indexes :content, type: :text, analyzer: 'english' end end end
Index Existing Records: After setting up your model, you need to index your existing records:
ruby:Post.import # for importing all records to Elasticsearch
Step 5: Implement Search Functionality
Add a Search Method in Your Model:
ruby:class Post < ApplicationRecord include Elasticsearch::Model include Elasticsearch::Model::Callbacks settings do mappings dynamic: false do indexes :title, type: :text, analyzer: 'english' indexes :content, type: :text, analyzer: 'english' end end def self.search(query) __elasticsearch__.search( { query: { multi_match: { query: query, fields: ['title^10', 'content'] } } } ) end end
Create a Controller Action for Search: In your controller, add a search action:
ruby;class PostsController < ApplicationController def search @posts = Post.search(params[:query]).records end end
Add a Route for Search: In your
config/routes.rb
:ruby:get 'search', to: 'posts#search'
Create a View for Search: Create a search view
app/views/posts/search.html.erb
:<h1>Search Results</h1> <%= form_with url: search_path, method: :get do %> <%= text_field_tag :query, params[:query] %> <%= submit_tag 'Search' %> <% end %> <% @posts.each do |post| %> <div> <h2><%= post.title %></h2> <p><%= post.content %></p> </div> <% end %>
Elastic::Transport::Transport::Errors::NotFound: no such index [posts]
, indicates that the Elasticsearch index for your Post
No comments:
Post a Comment