【问题标题】:How can I create a index in Elasticsearch with `go-elasticsearch` library?如何使用“go-elasticsearch”库在 Elasticsearch 中创建索引?
【发布时间】:2022-10-07 04:09:18
【问题描述】:

我在go 中使用这个库作为 Elasticsearch 客户端:https://pkg.go.dev/github.com/elastic/go-elasticsearch/esapi#IndicesCreate.WithBody

我在用这个库创建新索引时遇到问题。文档说这种方法:

type IndicesCreate func(index string, o ...func(*IndicesCreateRequest)) (*Response, error)

这看起来像是我可以用来创建索引的那个。但我是go 的新手,不知道如何传递第二个参数。

下面是我的代码:

req := esapi.IndicesCreateRequest{
        Index: indexName,
    }
    esapi.IndicesCreate(indexName, &req)

但我收到了too many arguments in conversion to esapi.IndicesCreate 错误消息。正确的方法是什么?

    标签: go elasticsearch


    【解决方案1】:

    根据这篇文章:

    你所要做的就是:

    export ES_INDEX=products # Linux, MacOS
    set ES_INDEX=products # Windows
    
    package main
    
    import (
        "errors"
        "log"
        "os"
    
        elasticsearch "github.com/elastic/go-elasticsearch/v8"
    )
    
    var (
        IndexNameEmptyStringError = errors.New("index name cannot be empty string")
        IndexAlreadyExistsError   = errors.New("elasticsearch index already exists")
    )
    
    func main() {
        index := os.Getenv("ES_INDEX")
        if index == "" {
            log.Fatal(IndexNameEmptyStringError)
        }
    
        elastic, err := elasticsearch.NewClient(elasticsearch.Config{
            Addresses: []string{"http://localhost:9200"},
        })
    
        if err != nil {
            log.Fatal(err)
        }
    
        response, err := elastic.Indices.Exists([]string{index})
        if err != nil {
            log.Fatal(err)
        }
    
        if response.StatusCode != 404 {
            log.Fatal(IndexAlreadyExistsError)
        }
    
        response, err = elastic.Indices.Create(index)
        if err != nil {
            log.Fatal(err)
        }
    
        if response.IsError() {
            log.Fatal(err)
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-06-19
      • 2016-08-20
      • 2018-04-07
      • 2021-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-06
      相关资源
      最近更新 更多