需要使用elasticsearch-ruby 在elasticsearch 索引中进行批量更新插入。任何帮助将不胜感激。
最佳答案
基本上,您正在构建一系列 elasticsearch 操作,可以使用下面的第二个代码块批量发送这些操作。这里最主要的是了解每个操作所需的语法,这应该有助于向您展示删除/索引/更新是如何工作的。
注意:data_hash 是通过查询模型并在返回的模型上使用 elasticsearch 辅助方法“.as_indexed_json”来生成的。这就是您在现有 Elasticsearch 记录上索引或更新的数据。删除显然不需要这个。
# operations is an array of model ids and the operation you want to perform on them
batch_for_bulk = []
operations.each do |id, operation|
data_hash = YourModel.find(id).as_indexed_json
if operation == 'delete'
batch_for_bulk.push({ delete: { _id: id}})
elsif operation == 'index'
batch_for_bulk.push({ index: { _id: id, data: data_hash}})
elsif operation == 'update'
batch_for_bulk.push({ update: { _id: id, data: {doc: data_hash}}})
end
end
以下是如何发送带有一些保护的请求
begin
YourModel.__elasticsearch__.client.bulk(
index: YourModel.index_name,
body: batch_for_bulk
) if batch_for_bulk.present?
rescue Faraday::TimeoutError
# handle your errors here
end
希望这对您有帮助!
关于ruby - ElasticSearch-ruby : Bulk Upsert,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44371888/