ElasticSearch-ruby:Bulk Upsert

时间:2017-06-05 15:03:07

标签: ruby elasticsearch

需要使用elasticsearch-ruby在elasticsearch索引中进行批量upsert。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

基本上,您正在构建一个Elasticsearch操作数组,可以与下面的第二个代码块一起批量发送。这里最主要的是要知道每个操作所需的语法,这应该有助于向您展示delete / index / update的工作方式。

注意: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

希望这会有所帮助!