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

1

2

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
Stately answered 5/8, 2017 at 19:12 Comment(6)
Paras, is the Product.import line in the product.rb file? And you should create two questions, becuse you are asking two things in this question.Hiller
Yes it is. Sure I would do that. Thanks.Stately
@Hiller where should the Product.import line be?Cheroot
@ManoharsinhRana it should be in a script that u should run for migrating from you DB to ElasticSearchHiller
@Hiller If I run Product.import in rails console in the terminal will this work?Cheroot
@ManoharsinhRana yep, it's something that's added when u include the Elasticsearch::Model moduleHiller
H
4

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.

Hiller answered 5/8, 2017 at 19:46 Comment(1)
You can also do it all in oneline with: Product.import force: trueChesterchesterfield

© 2022 - 2024 — McMap. All rights reserved.