如何使用golang SDK检查couchbase文档是否存在而不检索完整内容?

时间:2018-03-15 09:56:43

标签: go couchbase gocb

在我的代码中,我想要做或不做某些操作,具体取决于给定密钥存在的文档。但无法避免额外的网络开销检索所有文档内容。

现在我正在使用

cas, err := bucket.Get(key, &value)

并寻找err == gocb.ErrKeyNotFound来确定错过的案件。

是否有更有效的方法?

1 个答案:

答案 0 :(得分:4)

您可以使用sub-document API并检查是否存在字段。

来自Using the Sub-Document API to get (only) what you want 的示例:

rv = bucket.lookup_in('customer123', SD.exists('purchases.pending[-1]'))
rv.exists(0) # (check if path for first command exists): =>; False

编辑:添加示例

您可以使用子文档API检查文档是否存在,如下所示:

frag, err := bucket.LookupIn("document-key").
    Exists("any-path").Execute()

if err != nil && err == gocb.ErrKeyNotFound {
    fmt.Printf("Key does not exist\n")
} else {
    if frag.Exists("any-path") {
        fmt.Printf("Path exists\n")
    } else {
        fmt.Printf("Path does not exist\n")
    }
}