gpt4 book ai didi

ruby - ElasticSearch-ruby : Bulk Upsert

转载 作者:行者123 更新时间:2023-12-03 00:06:50 26 4
gpt4 key购买 nike

需要使用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com