I use elasticsearch-model
gem to integrate elasticsearch with activerecord, I am using this module:
#http://www.codinginthecrease.com/news_article/show/409843?referrer_id=
module PostImport
def self.import
Post.find_in_batches do |posts|
bulk_index(posts)
end
end
def self.prepare_records(posts)
posts.map do |post|
{ index: { _id: post.id, data: post.as_indexed_json } }
end
end
def self.delete_index
Post.__elasticsearch__.client
.indices.delete index: ::Post.__elasticsearch__.index_name rescue nil
end
def self.create_index
Post.__elasticsearch__.create_index!
end
def self.bulk_index(posts)
Post.__elasticsearch__.client
.bulk({
index: ::Post.__elasticsearch__.index_name,
type: ::Post.__elasticsearch__.document_type,
body: prepare_records(posts),
refresh: true
})
end
end
According to elasticsearch-model example
It uses this to create indexes in bulk:
client.bulk index: 'articles',
type: 'article',
body: Article.all.as_json.map { |a| { index: { _id: a.delete('id'), data: a } } },
refresh: true
But this raises:
Elasticsearch::Transport::Transport::Errors::NotFound: [404] {"error":"IndexMissingException[[posts] missing]","status":404}
from /home/ubuntu/.rvm/gems/ruby-2.1.3/gems/elasticsearch-transport-1.0.6/lib/elasticsearch/transport/transport/base.rb:132:in `__raise_transport_error'
So the equivalent code in my module: PostImport::import
raises this exception, If I call Post.__elasticsearch__.create_index!
first, and then do import, it works fine.
What is the proper way to initialize elasticsearch and create indexes with elasticsearch-model
gem?