登录
首页 >  Golang >  Go问答

在 Golang 中,避免插入已经存在于 Elasticsearch 中的文档

来源:stackoverflow

时间:2024-02-14 11:54:24 207浏览 收藏

珍惜时间,勤奋学习!今天给大家带来《在 Golang 中,避免插入已经存在于 Elasticsearch 中的文档》,正文内容主要涉及到等等,如果你正在学习Golang,或者是对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)

如果能得到一些帮助那就太好了!预先感谢您!


正确答案


esapi 中有一个 api 可用于检查特定索引中是否存在文档 id。

ExistRequest - 通过检查此请求响应的状态代码,我们可以确认该文档 id 是否存在(如果存在则为 200,如果不存在则为 404)

// 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")
}

终于介绍完啦!小伙伴们,这篇关于《在 Golang 中,避免插入已经存在于 Elasticsearch 中的文档》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>