package com.github.ingarabr.mi;

import org.elasticsearch.client.Client;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class EsWriter implements Runnable {

    private static final Logger logger = LoggerFactory.getLogger(EsWriter.class);

    private final Client esClient;
    private final BlockingQueue<String> writeQueue = new LinkedBlockingQueue<String>();

    private boolean run = true;

    public EsWriter(Client esClient) {
        this.esClient = esClient;
    }

    public void run() {
        try {
            while (run) {
                String metric = writeQueue.take();
                log();
                if (metric != null) {
                    esClient.prepareIndex("metrics", "metric").setSource(metric).get();
                }
            }
        } catch (InterruptedException e) {
            logger.warn("Interrupted", e);
        }
    }

    private void log() {
        if (writeQueue.size() > 10) {
            logger.debug("ElasticSearch WriteQueue size: {}", writeQueue.size());
        }
    }

    public void addMetric(String metric) {
        writeQueue.add(metric);
    }

    public void stop() {
        run = false;
    }

}

@@ -66,16 +66,257 @@
 Client;%0A
+import org.elasticsearch.common.joda.time.DateTime;%0Aimport org.elasticsearch.common.joda.time.DateTimeZone;%0Aimport org.elasticsearch.common.joda.time.format.DateTimeFormat;%0Aimport org.elasticsearch.common.joda.time.format.DateTimeFormatter;%0A
 import o
@@ -328,24 +328,24 @@
 f4j.Logger;%0A
-
 import org.s
@@ -584,16 +584,106 @@
 .class);
+%0A    private static final DateTimeFormatter DTF = DateTimeFormat.forPattern(%22yyyy.MM.dd%22);
 %0A%0A    pr
@@ -1085,24 +1085,122 @@
  != null) %7B%0A
+                    String indexName = %22metrics-%22 + DateTime.now(DateTimeZone.UTC).toString(DTF);%0A
             
@@ -1233,17 +1233,17 @@
 dex(
-%22metrics%22
+indexName
 , %22m

Index per day.