Tuesday, 18 June 2024

How to use elasticsearch for searching step by step

  1. Add the elasticsearch and elasticsearch-model gems: Add these to your Gemfile:

    ruby
    gem 'elasticsearch-model' gem 'elasticsearch-rails'

    Then run:

    sh
    bundle install

Step 3: Configure Elasticsearch in Rails

  1. Create an Elasticsearch Configuration File: Create a file named config/elasticsearch.yml with the following content:

    yaml
    development: url: http://localhost:9200 test: url: http://localhost:9200 production: url: <your-production-elasticsearch-url>
  2. Create an Initializer: Create an initializer file config/initializers/elasticsearch.rb:

    ruby
    Elasticsearch::Model.client = Elasticsearch::Client.new host: ENV['ELASTICSEARCH_URL'] || 'localhost:9200'

Step 4: Integrate Elasticsearch with Your Models

  1. Include Elasticsearch in Your Model: Let's say you have a Post model. Include Elasticsearch and its necessary modules:

    ruby
    class Post < ApplicationRecord include Elasticsearch::Model include Elasticsearch::Model::Callbacks end
  2. Customize Your Elasticsearch Index: You can customize how your model is indexed. Add an index definition to 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 end
  3. 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

  1. 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
  2. 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
  3. Add a Route for Search: In your config/routes.rb:

    ruby:
    get 'search', to: 'posts#search'
  4. 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 %>


++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

after used this code i am getting this errors Elastic::Transport::Transport::Errors::NotFound in Posts#search Showing /home/bittern/Desktop/rinku/projects/simple_dummy/app/views/posts/search.html.erb where line #7 raised:

[404] {"error":{"root_cause":[{"type":"index_not_found_exception","reason":"no such index [posts]","resource.type":"index_or_alias","resource.id":"posts","index_uuid":"na","index":"posts"}],"type":"index_not_found_exception","reason":"no such index [posts]","resource.type":"index_or_alias","resource.id":"posts","index_uuid":"na","index":"posts"},"status":404}

ChatGPTThe error you are encountering, Elastic::Transport::Transport::Errors::NotFound: no such index [posts], indicates that the Elasticsearch index for your Post

Steps to Resolve the Error

  1. Create the Index: Use the import method to create the index and populate it with your existing records. Run the following command in your Rails console:

    ruby
    Run: Post.import(force: true)

    This command will create the posts index in Elasticsearch and add all existing Post records to the index.

    Ager Ye wala step chal rha hai to Second wala nhi chalana (2. Ensure Elasticsearch is Running)

  2. Ensure Elasticsearch is Running: Make sure that your Elasticsearch service is running. You can check the status of Elasticsearch with the following command:

    sh
    Run: sudo systemctl status elasticsearch

    If it is not running, start it with:

    sh
    sudo systemctl start elasticsearch
  3. Check Elasticsearch Connection: Verify that your Rails application can connect to Elasticsearch. You can do this by testing a simple query in the Rails console:

    ruby
    Post.__elasticsearch__.client.cluster.health

    This should return the health status of your Elasticsearch cluster.

  4. you can use the following steps:

    1. Delete the Existing Index: You can delete the existing index using the Rails console:

      ruby

      Run: Post.__elasticsearch__.client.indices.delete index: Post.index_name
    2. Recreate and Populate the Index: After deleting the index, recreate and populate it with:

      ruby:
      Run: Post.__elasticsearch__.create_index!(force: true) Run: Post.import

No comments:

Post a Comment