A newer version of this documentation is available.

View Latest

Function: Advanced REPLACE operation

    March 16, 2025
    + 12

    Goal: Perform the Advanced REPLACE operation where Eventing interacts with the Data service.

    • This function advancedReplaceOp merely demonstrates the Advanced REPLACE operation.

    • Requires Eventing Storage (or metadata collection) and a "source" collection.

    • Needs a Binding of type "bucket alias" (as documented in the Scriptlet).

    • Will operate on any mutation where doc.type === "control_adv_replace".

    • Always tries to insert the test document, any insert error will be ignored.

    • There are 3 modes of operation: no_cas, bad_cas, and good_cas.

    • For more information refer to Advanced REPLACE operation in the detailed documentation.

    javascript
    // To run configure the settings for this Function, advancedReplaceOp, as follows: // // Version 7.0+ // "Listen to Location" // bulk.data.source // "Eventing Storage" // rr100.eventing.metadata // Binding(s) // 1. "binding type", "alias name...", "bucket.scope.collection", "Access" // "bucket alias", "src_col", "bulk.data.source", "read and write" // // Version 6.6.1 // "Source Bucket" // source // "MetaData Bucket" // metadata // Binding(s) // 1. "binding type", "alias name...", "bucket", "Access" // "bucket alias", "src_col", "source", "read and write" function OnUpdate(doc, meta) { if (!meta.id.startsWith("control_adv_replace")) return; log('input meta', meta); log('input doc ', doc); // Setup, make sure we have our doc to "replace", ignore any errors couchbase.insert(src_col,{"id":"test_adv_replace:" + doc.ins_id},{"a:": 1}); var new_meta; if (doc.mode && doc.mode === "no_cas") { // Here we pass no CAS it will always succeed new_meta = {"id":"test_adv_replace:" + doc.ins_id}; // optional set an expiry 60 seconds in the future // new_meta.expiry_date = new Date(Date.now() + 60 * 1000); } if (doc.mode && doc.mode === "bad_cas") { // Here we pass a non-matching CAS it will always fail new_meta = {"id":"test_adv_replace:" + doc.ins_id, "cas":"1111111111111111111"}; } if (doc.mode && doc.mode === "good_cas") { // Here we will pass the matching or current CAS it will succeed var tmp_r = couchbase.get(src_col,{"id":"test_adv_replace:" + doc.ins_id}); if (tmp_r.success) { // Here we use the current CAS just read via couchbase.get(...) new_meta = {"id":"test_adv_replace:" + doc.ins_id, "cas": tmp_r.meta.cas}; } else { log('Cannot replace due to no such key',"test_adv_replace:" + doc.ins_id); return; } } var new_doc = {id: doc.ins_id, type: "test_adv_replace", random: Math.random()}; var result = couchbase.replace(src_col,new_meta,new_doc); if (result.success) { log('success adv. replace: result',result); } else { log('failure adv. replace: id',new_meta.id,'result',result); } }