ruby-on-rails - 为 Rails 模型创建 Elasticsearch 索引时如何修复“非法参数异常”?
问题描述
我正在尝试将 Elasticsearch 集成到我的 rails 应用程序中。当我尝试对我的模型进行导入时,问题就出现了。视频.__elasticsearch__.import。
因此,在 Rails 控制台中,我运行了Video.__elasticsearch__.import。我收到此错误: 不存在要导入的 myflix_development。使用创建索引!或 :force 选项来创建它。
然后我运行Video.__elasticsearch__.create_index!和Video.__elasticsearch__.create_index!(force: true)并且它们都返回了相同的非法参数异常错误:
PUT http://localhost:9200/myflix_development [status:400, request:0.027s, query:N/A]
2019-06-08 11:18:29 +0800: > {"settings":{},"mappings":{"_doc":{"properties":{}}}}
2019-06-08 11:18:29 +0800: < {"error":{"root_cause":[{"type":"illegal_argument_exception","reason":"The mapping definition cannot be nested under a type [_doc] unless include_type_name is set to true."}],"type":"illegal_argument_exception","reason":"The mapping definition cannot be nested under a type [_doc] unless include_type_name is set to true."},"status":400}
我知道当我尝试导入时我应该创建一个弹性搜索索引,但我得到了这个非法参数异常,我对此感到困惑
这就是我所做的设置:
1)在我的gemfile中包含gem:
gem 'elasticsearch-model'
gem 'elasticsearch-rails'
2) 包含一个初始化程序:app/config/initializers/elasticsearch.rb
Elasticsearch::Model.client =
if Rails.env.staging? || Rails.env.production?
Elasticsearch::Client.new url: ENV['SEARCHBOX_URL']
elsif Rails.env.development?
Elasticsearch::Client.new log: true
else
Elasticsearch::Client.new
end
3) 在我的视频模型中包含弹性搜索
class Video < ActiveRecord::Base
include Elasticsearch::Model
index_name ["myflix", Rails.env].join("_")
...
end
4) Gemfile.lock
elasticsearch (7.1.0)
elasticsearch-api (= 7.1.0)
elasticsearch-transport (= 7.1.0)
elasticsearch-api (7.1.0)
multi_json
elasticsearch-model (6.0.0)
activesupport (> 3)
elasticsearch (> 1)
hashie
elasticsearch-rails (6.0.0)
elasticsearch-transport (7.1.0)
faraday
multi_json
任何帮助将不胜感激!
编辑 1) 尝试在我的模型中进行手动映射
class Video < ActiveRecord::Base
include Elasticsearch::Model
settings index: { number_of_shards: 1 } do
mappings dynamic: 'false' do
indexes :title, type: 'text'
indexes :description, type: 'text'
end
end
...
end
解决方案
您可以通过设置显式定义elasticsearch-model
传递给 Elasticsearch的文档类型document_type
。例如:
class Video < ActiveRecord::Base
include Elasticsearch::Model
index_name ["myflix", Rails.env].join("_")
document_type "video"
...
end
您使用的名称是任意的。只要不是_doc
,您就不会在 v7 及更高版本上遇到此错误。
推荐阅读
- powershell - New-NetIPAddress 参数“-IPAddress”导致“语句块或类型定义中缺少关闭 '}'”错误
- hadoop - 有没有办法为 Hive 中的表提供“第二个名称”,以便用户可以引用表的任一名称并检索相同的内容?
- kubernetes - 入口将域 www 重写为非 www url
- r - 层次聚类中质心链接背后的直觉是什么?
- java - 我应该如何命名一个只有 getter 的 Java 类?
- go - 如何在 Hana DB 上连接 SSL - SAP [SQL 错误 4321 - 只允许安全连接]
- c# - 如何使用 C# 代码使用命令 azure cli 导出数据库
- ios - 如何在 SwiftUI 的导航栏中添加“副标题”之类的内容?
- flutter - 尝试调用我的 getter 时,我得到了 Invalid argument(s)
- java - 如何将 jar 导入 Knime 中的 java 片段节点