1

In my code I want to do or not to do some actions depending on document with given key existence. But can't avoid additional network overhead retrieving all document content.

Now I'm using

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

And looking for err == gocb.ErrKeyNotFound to determine document missed case.

Is there some more efficient approach?

mind_religion
  • 75
  • 1
  • 10

1 Answers1

4

You can use the sub-document API and check for the existence of a field.

Example from 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

Edit: Add go example

You can use the sub-document API to check for document existence like this:

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")
    }
}
Jeff Kurtz
  • 651
  • 4
  • 8
  • In my case document can have no fields, or some of them. It's a map actually and I can't know for sure that particular field is exists – mind_religion Mar 15 '18 at 14:04
  • @mind_religion, please see my edit. You can still use the sub-document API in your situation. Perhaps a feature request is in order, to add something to `gocb.Bucket`: [Couchbase Go SDK Issue Tracker](https://issues.couchbase.com/browse/GOCBC). – Jeff Kurtz Mar 15 '18 at 17:13
  • But how we handle if real error with cb happens here? – mind_religion Mar 22 '18 at 17:51