ruby - ElasticSearch-ruby : Bulk Upsert

标签 ruby elasticsearch

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

相关文章:

ruby - 使用 Savon 进行 HTTPS 调用

ruby - 验证带有扩展名的电话号码格式

elasticsearch - 如何从存储桶聚合中获取最大值或平均值

ruby-on-rails - 在数据库列中存储逗号分隔的列表,如何获取和设置?

ruby-on-rails - Rails 6 具有强参数的嵌套资源

elasticsearch - kibana中的脚本化字段有时用于缺少的字段

elasticsearch - elasticsearch更新一套

amazon-web-services - 如何将数据从Amazon S3传输到Amazon EC2

elasticsearch - Elasticsearch嵌套过滤器包含与不包含

ruby - 按值对嵌套哈希中的项目进行排序