Small example how to delete documents from Elasticsearch using program in golang. Query contains both term query and range query. Column “@timestamp” is unix timestamp in miliseconds. Of course on Elasticsearch 2.x you must install plugin “delete by query” (

/usr/share/elasticsearch/bin/plugin install delete-by-query

).

package main

import (
	"log"
	"time"

	"fmt"

	elastic "gopkg.in/olivere/elastic.v3"
)

func main() {

	client, err := elastic.NewClient(elastic.SetURL("localhost:9200"))
	if err != nil {
		log.Fatal("Cannot create ES client:", err)
	}

	fromUnix := getUnixStamp("2017-03-01")
	toUnix := getUnixStamp("2017-03-06")

	fmt.Println(fromUnix, ":", toUnix)

	bq := elastic.NewBoolQuery()
	bq.Must(elastic.NewTermQuery("term1", "value1"))
	bq.Must(elastic.NewTermQuery("term2", "value2"))
	bq.Must(elastic.NewRangeQuery("@timestamp").Gte(fromUnix).Lte(toUnix))
	resp, err := elastic.NewDeleteByQueryService(client).
		Index("myindex").
		Type("mytype").
		Query(bq).
		Do()

	fmt.Println("resp:", resp)

}

func getUnixStamp(d string) int64 {
	layout := "2006-01-02"
	t, err := time.Parse(layout, d)
	if err != nil {
		log.Fatal("cannot parse date:", err)
	}
	u := t.Unix() * 1000
	return u
}