Hi, I’m experimenting with eventing functions, and I need to increment a counter which is inside an object, that has a variable key. Using the standard subdoc API I’d use the counter
function to increase the value.
Now, using eventing functions, I’m wondering what’s the best way to do it.
- Exploring the docs I noticed the sentence “Other advanced Data Service operations are available as member Functions on the map object.”, but I have no clue nor further reference to understand what’s available and where.
- I also tried some weird N1QL, like
UPDATE myBucket USE KEYS["myDocId"] SET $counterKey = $counterKey + 1;
, but function compilation fails on the first usage of$counterKey
, as object key.
Is there something I can do about it, without fetching/setting the whole document? I cannot perform a full fetch/set operation because I noticed that, if there are many events fired in few milliseconds, the set operations overlap each other and the counter is not increased properly (I guess some workers are performing the same operation in parallel, overwriting each other documents. Also, the issue happens even if I’m using a single worker on a single node).
Also, inspecting the logs and source code I noticed that the N1QL query was translated to an expression with a function similar to execQuery
at the end (maybe this one
?). Would there be an alternative syntax that I could use for my case? To be able to use a variable as key for the N1QL query?
UPDATE:
So, I managed to get it working by using:
const updated = new N1qlQuery(
`UPDATE \`myBucket\` USE KEYS["countersDocId"]
SET \`${counterBaseKey}\` =
CASE WHEN \`${counterBaseKey}\` IS MISSING THEN 1
ELSE \`${counterBaseKey}\` + 1 END RETURNING \`${counterBaseKey}\``,
{namedParams: {}}
).execQuery();
BUT, this sounds just slightly hackish . Is there a better and maybe also more code-stable way?
UPDATE 2:
Even though the N1QL query works, there is still some inconsistency , out of 40 runs in few milliseconds, I can see that some of the updates return the same counter value.
E.g.
2018-11-14T18:00:01.172+00:00 [INFO] "Triggered counter update"
2018-11-14T18:00:01.174+00:00 [INFO] "Update succeeded" [{"testEvent_tag2":3}]
2018-11-14T18:00:01.174+00:00 [INFO] "Triggered counter update"
2018-11-14T18:00:01.175+00:00 [INFO] "Update succeeded" [{"testEvent_tag2":3}]
Thanks,
Alberto