Skip to content

Instantly share code, notes, and snippets.

@olivere
Created May 17, 2018 13:22
Show Gist options
  • Save olivere/56cc0b13a25b79dad23d14df6ff5f682 to your computer and use it in GitHub Desktop.
Save olivere/56cc0b13a25b79dad23d14df6ff5f682 to your computer and use it in GitHub Desktop.
Issue #774: Create and delete index
package main
import (
"context"
"log"
"github.com/olivere/elastic"
)
const (
indexName = "films"
mapping = `
{
"settings":{
"number_of_shards":1,
"number_of_replicas":0
},
"mappings":{
"_doc":{
"properties":{
"title":{
"type":"keyword"
},
"genre":{
"type":"keyword"
},
"year":{
"type":"long"
},
"director":{
"type":"keyword"
}
}
}
}
}
`
)
func main() {
log.Print("Connecting...")
opts := []elastic.ClientOptionFunc{
// Uncomment next line to show response from Elasticsearch
//elastic.SetTraceLog(log.New(os.Stdout, "", 0)),
}
client, err := elastic.NewClient(opts...)
if err != nil {
log.Printf("unable to connect: %v", err)
}
// Check if index exists
log.Print("Check if index exists...")
ctx := context.Background()
exists, err := client.IndexExists(indexName).Do(ctx)
if err != nil {
log.Fatalf("unable to check if index exists: %v", err)
}
if exists {
log.Print("Removing existing index...")
_, err = client.DeleteIndex(indexName).Do(ctx)
if err != nil {
log.Fatalf("unable to delete index: %v", err)
}
}
// Create index with mapping
log.Print("Create index with mapping...")
_, err = client.CreateIndex(indexName).Body(mapping).Do(ctx)
if err != nil {
log.Fatalf("unable to create index: %v", err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment