I am not sure whether it is correct or not. But I think that if I want to add new data or document into existing index in elasticsearch using olivere in golang, the only option available is to delete the index and re index the data.
This is my code :
package main
import (
"context"
"errors"
"github.com/olivere/elastic"
)
const (
indexName = "newera"
docType = "log"
appName = "myApp"
indexMapping = `{
"mappings" : {
"log" : {
"properties" : {
"category_id" : {
"type" : "text"
}
}
}
}
}`
)
type Log struct {
CategoryID string `json:"category_id"`
}
func main() {
client, err := elastic.NewClient(elastic.SetURL("http://localhost:9200"))
if err != nil {
panic(err)
}
err = createIndexWithLogs(client)
if err != nil {
panic(err)
}
// err = findAndPrintAppLogs(client)
// if err != nil {
// panic(err)
// }
}
func createIndexWithLogs(client *elastic.Client) error {
exists, err := client.IndexExists(indexName).Do(context.Background())
if err != nil {
return err
}
if exists {
client.DeleteIndex(indexName).Do(context.Background())
}
res, err := client.CreateIndex(indexName).Body(indexMapping).Do(context.Background())
if err != nil {
return err
}
if !res.Acknowledged {
return errors.New("CreateIndex was not acknowledged. Check that timeout value is correct.")
}
return addLogsToIndex(client)
}
func addLogsToIndex(client *elastic.Client) error {
for i := 0; i < 10; i++ {
l := Log{
CategoryID: "New Worlds",
}
_, err := client.Index().
Index(indexName).
Type(docType).
BodyJson(l).
Do(context.Background())
if err != nil {
return err
}
}
return nil
}
Does anyone have a solution?
Thanks