0

Is there a golang API similar to counter available in other couchbase SDK's that will help us to atomically increment certain fields inside a json document?

For example, I have a below struct with two fields which will be associated with a document D1

type Counter struct {
        c1 string `json:"c1"`
        c2 string `json:"c2"`
}

For every http request that comes in, I would like to do an atomic increment of c1 and c2. since it's within a json document, am not able to use GET and not sure how to use counter method using golang.

Anthon
  • 69,918
  • 32
  • 186
  • 246
Ram Kumar
  • 11
  • 2

1 Answers1

0

It's not possible to have an atomic counter within a document, you have two options to work around this:

1) Have your document reference separate atomic counters, rather than holding the counter value they'll just hold the key that points to the counter. Something like the json below, if you retrieved the document then to work with the counter you'd use the value in 'counter_key'.

{
  "id": "customer::1343"
  "name": "John Smith",
  "counter_key": "counter::customer::1343"
}

2) Your second option is to keep the field within the Json document that you want to increment, to be able to update this atomically you'll need to look at CAS which is a form of optimistic locking which will allow you to update the value within the actual document rather than having a separate counter, this method does introduce additional coding overhead and won't be as performant as a separate counter. You can read about more about CAS here: http://docs.couchbase.com/developer/dev-guide-3.0/retrieve-by-cas.html

There is also a nice succinct description here of Couchbase CAS here on Stack Overflow: What is CAS in nosql and how to use it?

Community
  • 1
  • 1
scalabilitysolved
  • 2,473
  • 1
  • 26
  • 31