Skip to content

Instantly share code, notes, and snippets.

@inqueue
Created February 6, 2018 16:42
Show Gist options
  • Save inqueue/ca412602168978d980b24cc42d436893 to your computer and use it in GitHub Desktop.
Save inqueue/ca412602168978d980b24cc42d436893 to your computer and use it in GitHub Desktop.

PUT _xpack/watcher/watch/purge_indices

{
  "trigger": {
    "schedule": {
      "interval": "24h"
    }
  },
  "input": {
    "search": {
      "request": {
        "indices": [
          ".watcher-history-*"
        ],
        "body": {
          "size": 0,
          "aggs": {
            "indices": {
              "terms": {
                "field": "_index"
              },
              "aggs": {
                "last_timestamp": {
                  "max": {
                    "field": "trigger_event.schedule.scheduled_time"
                  }
                },
                "aged_indices": {
                  "bucket_selector": {
                    "buckets_path": {
                      "lastTimestamp": "last_timestamp"
                    },
                    "script": "params.lastTimestamp < System.currentTimeMillis() - 2 * 24 * 3600 * 1000"
                  }
                }
              }
            }
          }
        }
      }
    }
  },
  "condition": {
    "script": {
      "inline": """
if (ctx.payload.aggregations.indices.buckets.size() < 1) return false; return true;
      """
    }
  },
  "transform": {
    "script": """
def results=ctx.payload.aggregations.indices.buckets.stream().map(i -> i.key).collect(Collectors.toList()); return ['results': results];
    """
  },
  "actions": {
    "delete_index": {
      "webhook": {
        "method": "DELETE",
        "host": "es.host.name",
        "port": 9200,
        "scheme": "https",
        "path": "{{#join}}ctx.payload.results{{/join}}",
        "auth": {
          "basic": {
            "username": "elastic",
            "password": "somepassword"
          }
        }
      }
    },
    "log_entry": {
      "logging": {
        "text": "[Watcher]: purging {{#join}}ctx.payload.results{{/join}}: older than 2 days"
      }
    }
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment