Skip to content

Instantly share code, notes, and snippets.

@s-tajima
Created March 3, 2014 03:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save s-tajima/9317833 to your computer and use it in GitHub Desktop.
Save s-tajima/9317833 to your computer and use it in GitHub Desktop.
Remove old indices on ElasticSearch
#!/usr/bin/env ruby
require 'pp'
require 'net/http'
require 'date'
require 'json'
endpoint = "http://<HOST>:<PORT>/"
expire_days = 7
def request(method, uri)
begin
uri = URI.parse(uri)
request = Net::HTTP.new(uri.host, uri.port)
response = request.__send__(method.downcase, uri.path)
response_json = JSON.parse(response.body)
rescue => ex
warn "[Error] #{ex.message}"
warn "[Error] #{ex.backtrace}"
return false
end
response_json
end
status = request("GET", endpoint + "_status")
if status["indices"].nil?
warn "[Error] Get Index list failed."
exit
end
status["indices"].each do |index_name, data|
index_prefix, year, month, day = index_name.scan(/^([\w\.\_]+)-(\d{4})\.([0-1][0-9])\.?([0-3][0-9])?/).flatten
if year.nil? || month.nil?
puts "[Info] target index: #{index_name} is unexpected index name."
next
end
day = "-1" if day.nil?
elapsed_days = (Date.today - Date.new(year.to_i, month.to_i, day.to_i)).to_i
if expire_days - elapsed_days > 0
puts "[Info] target index: #{index_name} is skipped."
next
end
unless request("DELETE", endpoint + index_name)
warn "[Error] target index: #{index_name} delete failed."
next
end
puts "[Info] target index: #{index_name} is deleted."
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment