【问题标题】:Rails 5: How to import data in Elastic Search and perform conditional search?Rails 5:如何在 Elastic Search 中导入数据并执行条件搜索?
【发布时间】:2018-01-13 11:56:15
【问题描述】:

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

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

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

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

【问题讨论】:

  • Paras,Product.importproduct.rb 文件中的行吗?你应该创建两个问题,因为你在这个问题中问了两件事。
  • 是的。我当然会那样做。谢谢。
  • @MatayoshiMariano Product.import 行应该在哪里?
  • @ManoharsinhRana 它应该在一个脚本中,你应该运行它来从你的数据库迁移到 ElasticSearch
  • @ManoharsinhRana 是的,这是在您包含 Elasticsearch::Model 模块时添加的内容

标签: ruby-on-rails ruby elasticsearch ruby-on-rails-5


【解决方案1】:

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

仔细查看line!self.index_exists? index: target_index,它会检查索引是否存在,如果不存在,则会引发错误。

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

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

Product.__elasticsearch__.create_index!
Product.import

我建议您阅读如何将您的模型映射到 elasticsearch 中的索引。 Link1Link2。因为为了查询,你需要了解你的索引是如何创建的。

【讨论】:

  • 您也可以通过Product.import force: trueProduct.import force: true 在线完成所有操作
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-20
  • 1970-01-01
  • 1970-01-01
  • 2017-12-29
  • 1970-01-01
  • 2012-02-15
相关资源
最近更新 更多