[英]How to continue indexing documents in elasticsearch(rails)?
所以我運行了這個命令, rake environment elasticsearch:import:model CLASS='AutoPartsMapper' FORCE=true
對rake environment elasticsearch:import:model CLASS='AutoPartsMapper' FORCE=true
文檔進行索引。在我的數據庫中,我有1000000條記錄=)...(我認為)需要一天的時間來建立索引這...在索引編制程序運行時,我的計算機關閉了...(我為2000000文檔編制了索引)是否可以繼續為文檔編制索引?
elasicsearch-rails
afaik中沒有此類功能,但是您可以編寫一個簡單的任務來做到這一點。
namespace :es do
task :populate, [:start_id] => :environment do |_, args|
start_id = args[:start_id].to_i
AutoPartsMapper.where('id > ?', start_id).order(:id).find_each do |record|
puts "Processing record ##{record.id}"
record.__elasticsearch__.index_document
end
end
end
使用bundle exec rake es:populate[<start_id>]
傳遞記錄,從該記錄開始下一個批處理。
請注意,這是一個簡單的解決方案,它將比批處理索引慢得多。
更新
這是一個批處理索引任務。 它快得多,並且可以自動檢測要繼續的記錄。 它確實假定先前導入的記錄以id順序遞增且沒有間隙的方式進行處理。 我沒有測試過,但是大多數代碼來自生產系統。
namespace :es do
task :populate_auto => :environment do |_, args|
start_id = get_max_indexed_id
AutoPartsMapper.find_in_batches(batch_size: 1000).where('id > ?', start_id).order(:id) do |records|
elasticsearch_bulk_index(records)
end
end
def get_max_indexed_id
AutoPartsMapper.search(aggs: {max_id: {max: {field: :id }}}, size: 0).response[:aggregations][:max_id][:value].to_i
end
def elasticsearch_bulk_index(records)
return if records.empty?
klass = records.first.class
klass.__elasticsearch__.client.bulk({
index: klass.__elasticsearch__.index_name,
type: klass.__elasticsearch__.document_type,
body: elasticsearch_records_to_index(records)
})
end
def self.elasticsearch_records_to_index(records)
records.map do |record|
payload = { _id: record.id, data: record.as_indexed_json }
{ index: payload }
end
end
end
如果您使用Rails 4.2+,則可以使用ActiveJob計划並使其運行。 所以,首先用這個生成它
bin/rails generate job elastic_search_index
這將使您執行類和方法:
class ElasticSearchIndexJob < ApplicationJob
def perform
# impleement here indexing
AutoPartMapper.__elasticsearch__.create_index! force:true
AutoPartMapper.__elasticsearch__.import
end
end
將sidekiq設置為您的活躍工作提供者,並從控制台使用以下命令啟動:
ElasticSearchIndexJob.perform_later
這將設置活動作業並在下一個空閑作業上執行它,但它將釋放您的控制台。 您可以使其保持運行狀態,並稍后在bash中檢查該過程:
ps aux | grep side
這會給你類似的東西: sidekiq 4.1.2 app[1 of 12 busy]
看看這篇解釋他們的帖子
http://ruby-journal.com/how-to-integrate-sidekiq-with-activejob/
希望能幫助到你
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.