如何在Elasticsearch中创建索引?

sigwle7e  于 2022-11-22  发布在  ElasticSearch
关注(0)|答案(1)|浏览(202)

我在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错误消息。正确的方法是什么?

s71maibg

s71maibg1#

新答案

根据这篇文章,这是对您的问题的回答:

package main

import (
    "log"
    "strings"

    "github.com/elastic/go-elasticsearch/v8"
)

func main() {

    client, err := elasticsearch.NewDefaultClient()
    if err != nil {
        log.Fatal(err)
    }

    index := "products"
    mapping := `
    {
      "settings": {
        "number_of_shards": 1
      },
      "mappings": {
        "properties": {
          "field1": {
            "type": "text"
          }
        }
      }
    }`

    res, err := client.Indices.Create(
        index,
        client.Indices.Create.WithBody(strings.NewReader(mapping)),
    )
    if err != nil {
        log.Fatal(err)
    }

    log.Println(res)
}

旧答案

根据这篇文章:

你要做的就是:
第一次

相关问题