Skip to content

Instantly share code, notes, and snippets.

@ianblenke
Last active November 18, 2021 00:14
Show Gist options
  • Star 30 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save ianblenke/6422bed17090bb4f1712 to your computer and use it in GitHub Desktop.
Save ianblenke/6422bed17090bb4f1712 to your computer and use it in GitHub Desktop.
elasticsearch trying to allocate a primary shard which is disabled

Allow routing allocations:

curl -XPUT localhost:9200/_cluster/settings -d '{
                "transient" : {
                    "cluster.routing.allocation.enable" : "all"
                }
        }'

Reallocate unassigned shards, allowing primary allocations:

curl -s localhost:9200/_cat/shards | grep UNASS | while read line ; do \
  read -a fields <<<"$line" ;
  curl -XPOST -d '{ 
    "commands" : [ 
      { 
        "allocate" : {
          "index" : "'${fields[0]}'",
          "shard" : '${fields[1]}',
          "node" : "elasticsearch-'$(hostname)'",
          "allow_primary": "true"
        }
      }
    ]
  }' http://localhost:9200/_cluster/reroute?pretty ; done
@c-goosen
Copy link

This is an amazing script. I am bookmarking it. Much appreciated

@nik9000
Copy link

nik9000 commented Mar 13, 2017

Just remember "allow_primary": true means "I'm ok with losing all the data that might have been in that shard". This script will lose data. If you are stuck and need to get unstuck then this'll do the job though. The shards will come back online, but you'll lose all the data that was in them.

@LucaWintergerst
Copy link

A better solution in 5.x is to run the allocation explain API first to find out why the shard is not assigned.
https://www.elastic.co/guide/en/elasticsearch/reference/current/cluster-allocation-explain.html
Often times the problem is very simple to solve, even without data loss.

@wahab-io
Copy link

In elastic 2.4.1 even after bringing the node up, elastic search didn't move the shards automagically. Have to use relocate api to move the unassigned nodes (due to node left) back to the node it self.

@rcousens
Copy link

Just a heads up, I used this on a 21 node cluster (Elasticsearch 1.7) where one node had fallen over and after restarting the node there was an individual shard in 2 separate indexes that wouldn't allocate. I used this script to force the cluster to allocate the shards in an attempt to get the cluster out of RED, and unsurprisingly it "reset" the shard entirely and I lost 20 million docs or so.

There is no allocation explain API on 1.7 so I still don't know what I'll do if this occurs in the future.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment