ruby-on-rails - rails 5 : How to import data in Elastic Search and perform conditional search?

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

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

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

但是随着我表中记录的增加,使用上述方法的搜索时间也增加了,所以我决定实现 Elasticsearch 。我正在使用两个 gem gem 'elasticsearch-model' 和 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

最佳答案

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

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

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

另一个选项是首先创建索引,然后进行导入:

Product.__elasticsearch__.create_index!
Product.import

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

关于ruby-on-rails - rails 5 : How to import data in Elastic Search and perform conditional search?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45525523/

相关文章:

c# - 对象内的 id 字段,用于 elasticsearch 的 NEST

ruby-on-rails - 在代理后面的 Ubuntu 上安装 Rails

ruby-on-rails - 如何编写迁移来重命名 Rails 中的 ActiveRecord 模型及其表?

java - 垂直x。如何创建真正的多语言 JVM 应用程序?

ruby-on-rails - 在 Ruby on Rails 中使用 chartkick 自定义工具提示

elasticsearch - elasticsearch中的多字段操作

php - Elasticsearch 或者匹配查询

ruby-on-rails - 如何使用 devise、rspec、capybara 和 mailspec 测试 devise 邮件传送

ruby-on-rails - 如何自动将 Heroku pgbackups 发送到 S3

ruby-on-rails - 如何将每个价格添加到当前价格?