Rails 5:如何在弹性搜索中导入数据并执行条件搜索?

我有一个名为Product的模型。 我提供了一个全文搜索来搜索产品并使用AngularJS在客户端生成预先输入。 搜索查询是正常的查询,如:

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

但是随着我在表格中的记录增长,使用上述方法的搜索时间增加了,所以我决定实现弹性搜索。 我正在使用两颗gem'elasticsearch-model'and gem 'elasticsearch-rails' 。 如何索引产品型号 。 我尝试使用这个Product._elasticsearch_.create_index!rails控制台中的命令,它给出了以下错误:

 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. 

以下是我的实现:

产品型号

 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 

您得到的错误是因为您没有创建products索引, 在这里您可以看到引发错误的gem的代码。

看看这一行 , !self.index_exists? index: target_index !self.index_exists? index: target_index ,检查索引是否存在,如果不是则引发错误。

所以你必须在这里强制导入这样的选项: Product.import(force: true) ,请注意这会破坏索引(如果它存在)并再次创建它。

另一种选择是首先创建索引然后执行导入:

 Product.__elasticsearch__.create_index! Product.import 

我建议您阅读如何将模型映射到elasticsearch中的索引。 Link1 , Link2 。 因为要进行查询,您需要了解索引的创建方式。