'How can I create a index in Elasticsearch with `go-elasticsearch` library?

I am using this library in go as Elasticsearch client: https://pkg.go.dev/github.com/elastic/go-elasticsearch/esapi#IndicesCreate.WithBody

I have a problem on creating a new index with this library. The doc says this method:

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

which looks like the one I can use to create the index. But I am new to go and not sure how to pass the second parameter.

Below is my code:

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

but I got too many arguments in conversion to esapi.IndicesCreate error message. What is the right way to do it?



Solution 1:[1]

According to this article:

All you have to do is:

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.Println(IndexNameEmptyStringError)
        os.Exit(1)
    }

    elastic, err := elasticsearch.NewClient(elasticsearch.Config{
        Addresses: []string{"http://localhost:9200"},
    })

    if err != nil {
        log.Println(err)
        os.Exit(1)
    }

    response, err := elastic.Indices.Exists([]string{index})
    if err != nil {
        log.Println(err)
        os.Exit(1)
    }

    if response.StatusCode != 404 {
        log.Println(IndexAlreadyExistsError)
        os.Exit(1)
    }

    response, err = elastic.Indices.Create(index)
    if err != nil {
        log.Println(err)
        os.Exit(1)
    }

    if response.IsError() {
        log.Println(err)
        os.Exit(1)
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1