Paras
Paras

Reputation: 3481

Rails 5: How to import data in Elastic Search and perform conditional search?

I have a model named Product. I provided a full text search to search products and producing a type-ahead on the client side using AngularJS. The search query was a normal like query as :

select * from products where name like = %abc% and company_id = 123;

However as my records in the table grew, the search time using the above method increased, so I decided to implement elastic search. I'm using two gems gem 'elasticsearch-model'and gem 'elasticsearch-rails'. How can I index the Product Model. I tried using this Product._elasticsearch_.create_index! command in the rails console it gave the following error :

2.4.0 :006 > Product._elasticsearch_.create_index!
ArgumentError: products does not exist to be imported into. Use create_index! or the :force option to create it.

Below are my implementations :

The Product Model

require 'elasticsearch/model'
class Product < ApplicationRecord
  include Elasticsearch::Model
  include Elasticsearch::Model::Callbacks
  belongs_to :company
  belongs_to :category
  belongs_to :gst
  belongs_to :user
  has_many :invoice_details
  self.per_page = 100

  Product.import
end

Upvotes: 2

Views: 3712

Answers (1)

MatayoshiMariano
MatayoshiMariano

Reputation: 2096

The error you are getting is because you do not have a products index created, here you can see the code of the gem where the error is raised.

Take a close look at this line, the !self.index_exists? index: target_index, it checks if the index exists, if not the error is Raised.

So you have two options here, to force the import like this: Product.import(force: true), be aware that this destroys the index if it exists and creates it again.

The other option is to first create the index an then do the import:

Product.__elasticsearch__.create_index!
Product.import

I recommend to you to read how to map your model to the index in elasticsearch. Link1, Link2. Because in order to query, you need to understand how your index is created.

Upvotes: 4

Related Questions