golang elasticSearch 删除 index (使用包 olivere/elastic)

Golang · Fecmall · 于 6年前 发布 · 4190 次阅读
package esdb
import (
    "context"
	// "encoding/json"
	"log"
	// "reflect"
	// "time"
    "sync"
    "errors"
	"github.com/olivere/elastic"
)

var once sync.Once
var esClient *(elastic.Client)
var esUrl string = "http://127.0.0.1:9200"


func Client() (*(elastic.Client), error){
    var err error
    once.Do(func() {
        // Starting with elastic.v5, you must pass a context to execute each service
        ctx := context.Background()

        // Obtain a client and connect to the default Elasticsearch installation
        // on 127.0.0.1:9200. Of course you can configure your client to connect
        // to other hosts and configure it in various other ways.
        /*
        client, err := elastic.NewClient(
            elastic.SetURL("http://127.0.0.1:9200", "http://127.0.0.1:9201"),
            elastic.SetBasicAuth("user", "secret"))

        */
        esClient, err = elastic.NewClient(elastic.SetURL(esUrl))
        if err != nil {
            return 
        }

        // Ping the Elasticsearch server to get e.g. the version number
        info, code, err := esClient.Ping(esUrl).Do(ctx)
        if err != nil {
            return 
        }
        log.Printf("Elasticsearch returned with code %d and version %s\n", code, info.Version.Number)

        // Getting the ES version number is quite common, so there's a shortcut
        esversion, err := esClient.ElasticsearchVersion(esUrl)
        if err != nil {
            return 
        }
        log.Printf("Elasticsearch version %s\n", esversion)
    })
    
    return esClient, err
}
// 通过indexName 删除 Index
func DeleteIndex(indexName string) error {
    var err error
    ctx := context.Background()
    client, err := Client()
    if err != nil {
		return err
	}
    exists, err := client.IndexExists(indexName).Do(ctx)
	if err != nil {
        log.Println("IndexExists" + err.Error())
		return err
	}
    if exists {
        deleteIndex, err := client.DeleteIndex(indexName).Do(ctx)
        if err != nil {
            // Handle error
            return err
        }
        if !deleteIndex.Acknowledged {
            // Not acknowledged
            return errors.New("delete index is not Acknowledged")
        }
    }
    return err
}
共收到 0 条回复
没有找到数据。
添加回复 (需要登录)
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册
Your Site Analytics