shicholas
shicholas

Reputation: 6153

IndexPrimaryShardNotAllocatedException error while trying to close an elasticsearch cluster

After installing elasticsearch on my machine using https://gist.github.com/wingdspur/2026107 which starts an elasticsearch cluster at http://localhost:9200, I am trying to create an index with settings and used this code:

  search_indices.create index: 'test'
  search_indices.refresh index: 'test'
  search_indices.close index: 'test'
  search_indices.put_settings(index: 'test', **my_index_settings)
  search_indices.put_mapping(index: 'test', **my_mapping_settings)
  search_indices.open index: 'test'

Where

search_indices = Elasticsearch::Client.new({host: 'http://localhost:9200'}).indices
# this module comes from the elasticsearch-ruby gem

When I execute this code, I get an error when I try to execute the 'close' method (line 3 above)

Elasticsearch::Transport::Transport::Errors::Conflict:
   [409] {"error":"IndexPrimaryShardNotAllocatedException[[test_1] primary not allocated post api]","status":409}

I have tried adding the refresh method (line 2 above) which sometimes work and sometimes doesn't, I have a feeling that 'sometimes working' means I'm doing something wrong. Thanks for the help!

Upvotes: 3

Views: 1412

Answers (1)

shicholas
shicholas

Reputation: 6153

So I stumbled upon the cluster health option with the ruby API now it seems to work.

Here is how I solved it:

def search_client
  # I should memoize this so I don't have to keep creating new indices
  @search_client ||= Elasticsearch::Client.new({host: 'http://localhost:9200'})
end

def search_indices
  search_client.indices
end

Then my code above looks like:

  search_indices.create index: 'test'
  search_client.cluster.health wait_for_status: 'green'
  search_indices.close index: 'test'
  search_indices.put_settings(index: 'test', **my_index_settings)
  search_indices.put_mapping(index: 'test', **my_mapping_settings)
  search_indices.open index: 'test'

Hope this helps someone!

Upvotes: 6

Related Questions