英文:
Dont insert document if already exists in Elasticsearch with Golang
问题
我是你的中文翻译助手,以下是翻译好的内容:
我刚开始学习golang,在Elasticsearch中插入具有相同id的新文档时遇到了困难。到目前为止,我可以正确地将文档插入索引中,但如果文档的id重复,时间戳会更新(因为这是唯一变化的内容)。然而,我希望的是不更新文档,换句话说,什么都不做。
在Python中,我通过以下方式实现了这一点:
es = Elasticsearch(
[elastic_url],
http_auth=(elastic_user, elastic_password),
verify_certs=True,
)
return es.create(index=index_name, id=document_id, body=data, ignore=409)
而在golang中,我使用以下代码:
req := esapi.IndexRequest{
Index: "test_index",
DocumentID: "2",
Body: strings.NewReader(data),
Refresh: "false",
}
res, err := req.Do(ctx, es)
如果能得到一些帮助就太棒了!提前谢谢!
英文:
I am new to golang and I'm struggling in inserting new documents with the same id in Elasticsearch. Until now I can insert the document correctly in the index, but if the document's id is repeated, the timestamp updates (because is the only thing that is changing). However, what I am looking to do is not to update the document, in other words, do nothing at all.
In the case of Python, to accomplish this I do the following thing:
es = Elasticsearch(
[elastic_url],
http_auth=(elastic_user, elastic_password),
verify_certs=True,
)
return es.create(index=index_name, id=document_id, body=data, ignore=409)
And in golang I'm using the following code:
req := esapi.IndexRequest{
Index: "test_index",
DocumentID: "2",
Body: strings.NewReader(data),
Refresh: "false",
}
res, err := req.Do(ctx, es)
It would be awesome some help! Thank you in advance!
答案1
得分: 1
在esapi
中有一个API可用于检查特定索引中文档ID的存在性。
ExistRequest - 通过检查来自该请求的响应的状态码,我们可以确认该文档ID是否存在(如果存在则为200,如果不存在则为404)
// 准备存在性检查请求
req := esapi.ExistsRequest{
Index: index,
DocumentID: id,
}
// 发送存在性检查请求
// 这里的client是*elastic.Client
ctx := context.Background()
resp, err := req.Do(ctx, client)
if err != nil {
// 处理错误
}
status := resp.StatusCode
if status == 200 {
fmt.Println("存在")
} else if status == 404 {
fmt.Println("未找到")
}
英文:
There is an API available in esapi
for checking existence of a document id in a particular index.
ExistRequest - By checking the status code of the response from this request we can confirm whether that document id is present or not (200 if present and 404 if not present)
// prepare existence checking request
req := esapi.ExistsRequest{
Index: index,
DocumentID: id,
}
// send existence checking request
// client here is *elastic.Client
ctx := context.Background()
resp, err := req.Do(ctx, client)
if err != nil {
// handle error
}
status := resp.StatusCode
if status == 200 {
fmt.Println("Exist")
} else if status == 404 {
fmt.Println("Not found")
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论