usage of BulkIndexRequest from golang package 'elastic'

huangapple go评论87阅读模式
英文:

usage of BulkIndexRequest from golang package 'elastic'

问题

我想使用Go包elastic中的BulkIndexRequest。我尝试查找示例,但似乎没有找到。所以如果有人使用过它,能否帮助我创建以下请求?

import (
    "context"
    "github.com/olivere/elastic/v7"
)

func main() {
    client, err := elastic.NewClient()
    if err != nil {
        // 处理错误
    }

    request := client.Bulk().Index("someindex").Type("sometype")

    // 添加第一个文档
    doc1 := map[string]interface{}{
        "index": map[string]interface{}{
            "_id": "existing_id",
        },
    }
    request.Add(doc1)

    // 添加第二个文档
    doc2 := map[string]interface{}{
        "field1": "test1",
    }
    request.Add(doc2)

    // 添加第三个文档
    doc3 := map[string]interface{}{
        "index": map[string]interface{}{
            "_id": "existing_id2",
        },
    }
    request.Add(doc3)

    // 添加第四个文档
    doc4 := map[string]interface{}{
        "field2": "test2",
    }
    request.Add(doc4)

    // 执行批量索引请求
    response, err := request.Do(context.Background())
    if err != nil {
        // 处理错误
    }

    // 处理响应
    // ...
}

请注意,上述代码仅为示例,你需要根据实际情况进行适当的修改和错误处理。

英文:

I want to use BulkIndexRequest from Go package elastic. I try to find examples but it seems that they don't exist. So if anybody has used it, could you please help me to use it for creating request something like below?

curl -s -H "Content-Type: application/json" -XPOST localhost:9200/someindex/sometype/_bulk -d'
{ "index": {"_id": "existing_id"}}
{ "field1": "test1"}
{ "index": {"_id": "existing_id2"}}
{ "field2": "test2"}
'

答案1

得分: 2

你可以在test classes中找到一些示例,并且在wiki中有很好的解释。它的用法如下:

indexName := "someindex"
typeName  := "sometype"
index1Req := NewBulkIndexRequest().Index(indexName).Type(typeName).Id("existing_id").Doc({...})
index2Req := NewBulkIndexRequest().Index(indexName).Type(typeName).Id("existing_id2").Doc({...})

bulkRequest := client.Bulk()
bulkRequest = bulkRequest.Add(index1Req)
bulkRequest = bulkRequest.Add(index2Req)

bulkResponse, err := bulkRequest.Do(context.TODO())
if err != nil {
	t.Fatal(err)
}
...
英文:

You can find a few examples in the test classes and is pretty well explained in the wiki. It goes like this:

indexName := "someindex"
typeName  := "sometype"
index1Req := NewBulkIndexRequest().Index(indexName).Type(typeName).Id("existing_id").Doc({...})
index2Req := NewBulkIndexRequest().Index(indexName).Type(typeName).Id("existing_id2").Doc({...})

bulkRequest := client.Bulk()
bulkRequest = bulkRequest.Add(index1Req)
bulkRequest = bulkRequest.Add(index2Req)

bulkResponse, err := bulkRequest.Do(context.TODO())
if err != nil {
	t.Fatal(err)
}
...

huangapple
  • 本文由 发表于 2017年7月26日 19:48:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/45326078.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定