Backup/restore Elasticsearch index

[UPDATED 2017-03-09]
I still get comments/questions regarding this process I hacked together many moons ago. I must request that anybody who’s looking for a way to backup Elasticsearch indices STOP and do not follow the process described — it was for ES 0.00000000001, written back in 2011. You should not do what I suggest here! I’m saving this purely for historical purposes.

What you should do instead is save your events in flat text — in Logstash, output to both your ES index for searching via Kibana or whatnot, and also output your event to a flat file, likely periodic (per-day or month or whatever). Backup and archive these text files, since they compress quite well. When you want to restore data from a period, just re-process it through Logstash — CPU is cheap nowadays with cloud instances! The data is the important part — processed or not, if you have the data in an easily stored format, you can re-process it.

[Original post as follows]

I’ve been spending a lot of time with Elasticsearch recently, as I’ve been implementing logstash for our environment. Logstash, by the way, is a billion times awesome and I can’t recommend it enough for large-scale log management/search. Elasticsearch is pretty awesome too, but considering the sheer amount of data I was putting into it, I don’t feel satisfied with its replication-based redundancy — I need backups that I can save and restore at will. Since logstash creates a new Elasticsearch index for each day worth of logs, I want the ability to backup and restore arbitrary indices.

Elasticsearch has a concept of a gateway, wherein you can configure a gateway that maintains metadata and snapshots are regularly taken. “Regularly” as in every 10 seconds by default. The docs recommend using S3 as a gateway, meaning every 10s it’ll ship data up to S3 for backup purposes, and if a node ever needs to recover data, it can just look to S3 and get the metadata and fill in data from that source. However, this model does not support the “rotation”-style backup and restore I’m looking for, and it can’t keep up with the rate of data I’m sending it (my daily indices are about 15gb apiece, making for about 400k log entries an hour).

So I’ve come up with a pair of scripts that allow me to manage logstash/Elasticsearch index data, allowing for arbitrary restore of an index, as well as rotation so as to keep the amount of data that Elasticsearch keeps track of manageable. As always, I wrote my scripts for my environment, so I take no responsibility if they do not work in yours and instead destroy all your data (a distinct possibility). I include these scripts here because I spent a while trying to figure this out and couldn’t find any information elsewhere on the net.

The following script backs up today’s logstash index. I’m retarded at timezones, so I managed to somehow ship my logs to logstash in GMT, so my “day” ends at 5pm, when logstash closes its index and opens a new one for the new day. Shortly after logstash closes an index (stops writing to it, not “close” in the Elasticsearch sense), I run the following script in cron, which backs up the index, backs up the metadata, creates a restore script, and sticks it all in S3:

# herein we backup our indexes! this script should run at like 6pm or something, after logstash
# rotates to a new ES index and theres no new data coming in to the old one. we grab metadatas,
# compress the data files, create a restore script, and push it all up to S3.

TODAY=`date +"%Y.%m.%d"`
INDEXNAME="logstash-$TODAY" # this had better match the index name in ES
BACKUPCMD="/usr/local/backupTools/s3cmd --config=/usr/local/backupTools/s3cfg put"
YEARMONTH=`date +"%Y-%m"`

# create mapping file with index settings. this metadata is required by ES to use index file data
echo -n "Backing up metadata... "
curl -XGET -o /tmp/mapping "http://localhost:9200/$INDEXNAME/_mapping?pretty=true" > /dev/null 2>&1
sed -i '1,2d' /tmp/mapping #strip the first two lines of the metadata
echo '{"settings":{"number_of_shards":5,"number_of_replicas":1},"mappings":{' >> /tmp/mappost 
# prepend hardcoded settings metadata to index-specific metadata
cat /tmp/mapping >> /tmp/mappost
echo "DONE!"

# now lets tar up our data files. these are huge, so lets be nice
echo -n "Backing up data files (this may take some time)... "
mkdir -p $BACKUPDIR
nice -n 19 tar czf $BACKUPDIR/$INDEXNAME.tar.gz $INDEXNAME 
echo "DONE!"

echo -n "Creating restore script... "
# time to create our restore script! oh god scripts creating scripts, this never ends well...
cat << EOF >> $BACKUPDIR/$
# this script requires $INDEXNAME.tar.gz and will restore it into elasticsearch
# it is ESSENTIAL that the index you are restoring does NOT exist in ES. delete it
# if it does BEFORE trying to restore data.

# create index and mapping
echo -n "Creating index and mappings... "
curl -XPUT 'http://localhost:9200/$INDEXNAME/' -d '`cat /tmp/mappost`' > /dev/null 2>&1
echo "DONE!"

# extract our data files into place
echo -n "Restoring index (this may take a while)... "
tar xzf $BACKUPDIR/$INDEXNAME.tar.gz
echo "DONE!"

# restart ES to allow it to open the new dir and file data
echo -n "Restarting Elasticsearch... "
/etc/init.d/es restart
echo "DONE!"
echo "DONE!" # restore script done

# push both tar.gz and restore script to s3
echo -n "Saving to S3 (this may take some time)... "
echo "DONE!"

# cleanup tmp files
rm /tmp/mappost
rm /tmp/mapping

Restoring from this data is just as you would expect — download the backed up index.tar.gz and the associated to the same directory, chmod +x the, then run it. It will automagically create the index and put the data in place. This has the benefit of making backed up indices portable — you can “export” them from one ES cluster and import them to another.

As mentioned, because of logstash, I have daily indices that I back up; I also rotate them to prevent ES from having to search through billions of gigs of data over time. I keep 8 days worth of logs in ES (due to timezone issues) by doing the following:

# Performs 'rotation' of ES indices. Maintains only 8 indicies (1 week) of logstash logs; this script
# is to be run at midnight daily and removes the oldest one (as well as any 1970s-era log indices,
# as these are a product of timestamp fail).  Please note the insane amount of error-checking
# in this script, as ES would rather delete everything than nothing...

# Before we do anything, let's get rid of any nasty 1970s-era indices we have floating around
TIMESTAMPFAIL=`curl -s localhost:9200/_status?pretty=true |grep index |grep log |sort |uniq |awk -F\" '{print $4}' |grep 1970 |wc -l`
		curl -s localhost:9200/_status?pretty=true |grep index |grep log |sort |uniq |awk -F\" '{print $4}' |grep 1970 | while read line
				echo "Indices with screwed-up timestamps found; removing"
				echo -n "Deleting index $line: "
				curl -s -XDELETE http://localhost:9200/$line/
				echo "DONE!"

# Get list of indices; should we rotate?
INDEXCOUNT=`curl -s localhost:9200/_status?pretty=true |grep index |grep log |sort |uniq |awk -F\" '{print $4}' |wc -l`
if [ $INDEXCOUNT -lt "9" ] 
		echo "Less than 8 indices, bailing with no action"
		exit 0
		echo "More than 8 indices, time to do some cleaning"
		# Let's do some cleaning!
		OLDESTLOG=`curl -s localhost:9200/_status?pretty=true |grep index |grep log |sort |uniq |awk -F\" '{print $4}' |head -n1`
		echo -n "Deleting oldest index, $OLDESTLOG: "
		curl -s -XDELETE http://localhost:9200/$OLDESTLOG/
		echo "DONE!"

Sometimes, due to the way my log entries get to logstash, the timestamp is mangled, and logstash, bless its heart, tries so hard to index it. Since logstash is keyed on timestamps, though, this means every once in a while I get an index dated 1970 with one or two entries. There’s no harm save for any overhead of having an extra index, but it also makes it impossible to back those up or to be able to make any assumptions about the index names. I nuke the 1970s indices from orbit, and then, if there are more than 8 indices in logstash, drop the oldest. I run this script at midnight daily, after index backup. Hugest caveat in the world about the rotation: running `curl -s -XDELETE http://localhost:9200/logstash-10.14.2011/’ will delete index logstash-10.14.2011, as you’d expect. However, if that variable $OLDESTLOG is mangled somehow and this command is run: `curl -s -XDELETE http://localhost:9200//’, you will delete all of your indices. Just a friendly warning!


  • twolf

    January 27, 2012

    Hi, what instance types are you using for the elasticsearch cluster?

  • kale

    January 27, 2012

    I have a pair of m1.large instances currently running my logstash cluster which works fairly well for my needs (high volume writes, low volume searches).

  • twolf

    January 27, 2012

    What throughput can you get with that for logstash writes/indexing? I have elasticsearch running on a single m1.large with EBS (5 shards, no replicas) and it seems to be maxing out at around 1000 events/sec (looks CPU bound). I’m about to try 2 m1.large and get rid of EBS.

  • kale

    January 27, 2012

    In my testing, I was seeing about the same as you (1000 event/s). My actual usage is currently just short of that; however, in my environment, logstash was the bottleneck (CPU), and running an additional logstash agent on another instance, storing to the same ES cluster, worked well. I don’t have the numbers handy, but “load balancing” logstash agents, if possible, helps with scalability.

  • twolf

    January 27, 2012

    I’m running logstash agents separately on m1.small instances in the autoscale group. It scales out whenever event queue starts to grow. But elasticsearch is definitely a bottleneck…

  • logstashuser

    April 19, 2013

    How does it work in a sharded environment? I see that you are backing up index directory /usr/local/elasticsearch/data/logstash/nodes/0/indices/ . Should this script be run on all shards?

  • Pingback: Elasticsearch Logstash index backup, restore, rotate - imperialWicket

  • Alex Gray

    July 15, 2013

    Thanks for this script!
    I’ve been testing these backup/restore scripts and it seems to work, regardless of the warnings from tar:

    tar: logstash-2013.07.15/0/index/_18j.tis: File removed before we read it
    tar: logstash-2013.07.15/0/index/_16u.fdt: file changed as we read it

    I don’t think I should be worried with those warnings, but I thought I’d ask just in case.

    On a side note, here are my stats:
    I have a ~25 m1.small’s (depending on what the Auto Scaling Group is doing) running logstash, shipping to a logstash indexer and so far so good, but I suspect we’ll be upgrading the elasticsearch/redis/logstash-indexer machine to a m1.large pretty soon.

  • Ryan Meyer

    March 6, 2014

    Curious how you are restoring the indexes on the file system. Are you excluding any files specifically? How are you handling the write.lock file in the index directory of each shard? I tried copying files to the new index but I get errors about a write lock file.

  • passerby

    October 27, 2014

    “However, if that variable $OLDESTLOG is mangled somehow and this command is run: `curl -s -XDELETE http://localhost:9200//‘, you will delete all of your indices.”

    Why not just check that $OLDESTLOG is not null before curling?

    if [ -n “$OLDESTLOG” ]; then go bananas; fi

  • valentyn

    May 29, 2015

    Thank you for article, it is very useful.

    I would like to improve the restoration procedure.
    Actually I can avoid restarting ElasticSearch. Instead you may follow such steps:
    – create Index: curl -XPUT ‘http://localhost:9200/$INDEXNAME/’ -d ‘`cat /tmp/mappost`’ > /dev/null 2>&1
    – close index: curl -XPOST ‘http://localhost:9200/$INDEXNAME/_close’
    – untar data
    – open index: curl -XPOST ‘http://localhost:9200/$INDEXNAME/_open’

    after recovery procedure index becomes available and cluster switches to Green state

  • Titi

    June 15, 2015

    Thanks for the scripts.
    I am a bit new to implementing an elk stack, and while I managed to setup everything ok, and tried out your backup scripts, I might be doing something wrong since the indices seem to come back after I delete them. Not immediately, but if I do a cleanup in the evening, by the time I check them in the morning all the indices I deleted are back in the folder.

    Is there some sort of setup I’m missing? Am I supposed to tell the logstash forwarder to stop sending old logs?
    I’m wondering whether other people have experienced this and what I can do about it? Thanks

  • SDC

    August 26, 2015

    Quick note to people of the future (after 2012 when this appears to have been written):

    Since 1.0 ElasticSearch has had Snapshot/Restore for your backup needs:

Leave a Reply