在沙发床中插入新记录时仅保留n条记录

时间:2020-06-08 07:07:58

标签: node.js couchbase couchbase-nodejs-sdk

我有一个巨大的存储桶,其中包含所有用户的通知数据。像这样:

┌────┬─────────┬─────────────────────────┐
│ id │ user_id │          data           │
├────┼─────────┼─────────────────────────┤
│  1 │       1 │ {"somekey":"someValue"} │
│  2 │       2 │ {"somekey":"someValue"} │
│  3 │       1 │ {"somekey":"someValue"} │
│  4 │       1 │ {"somekey":"someValue"} │
│  5 │       1 │ {"somekey":"someValue"} │
│  6 │       2 │ {"somekey":"someValue"} │
│  7 │       2 │ {"somekey":"someValue"} │
│  8 │       1 │ {"somekey":"someValue"} │
│  9 │       2 │ {"somekey":"someValue"} │
│ 10 │       2 │ {"somekey":"someValue"} │
└────┴─────────┴─────────────────────────┘

因此,无论何时我想插入新记录,例如user_id=2,我都想删除user_id=2的最早记录,以便每个用户只有N条记录(当然如果记录总数少于N,则不会删除)

2 个答案:

答案 0 :(得分:1)

@ehsan,另一种替代方法是使用Eventing Service,并将您的文档提供给Eventing函数。您可以使用ID(用于通知)和user_id的复合键。

例如,我使用“ nu:#:#”形式的键。然后,Eventing将处理您的数据或通知,以建立像@MatthewGroves建议的用户文档。

实际上,您可以选择在成功添加输入文档后将其删除。

请如下考虑您的输入键和文档:

┌──────────┬─────────────────────────┐
│ key      │  data                   │
├──────────┼─────────────────────────┤
│  nu:1:u1 │ {"somekey":"someValue"} │
│  nu:2:u2 │ {"somekey":"someValue"} │
│  nu:3:u1 │ {"somekey":"someValue"} │
│  nu:4:u1 │ {"somekey":"someValue"} │
│  nu:5:u1 │ {"somekey":"someValue"} │
│  nu:6:u2 │ {"somekey":"someValue"} │
│  nu:7:u2 │ {"somekey":"someValue"} │
│  nu:8:u1 │ {"somekey":"someValue"} │
│  nu:9:u2 │ {"somekey":"someValue"} │
│ nu:10:u2 │ {"somekey":"someValue"} │
└──────────┴─────────────────────────┘

现在,我们可以使用Eventing函数,其参数为MAX_ARRAY = 3(根据您的需要进行调整),以控制每个用户要保留的最大通知数。

请注意,我还添加了一个参数MAX_RETRY = 16,以便在发生争用(通过检查保存Math.random()的字段完成的可怜的CAS)进行重试。

我假定通知ID总是递增,因为JavaScript处理2 ^ 53 -1(或9,007,199,254,740,991),这应该不是问题。

正在运行的事件功能如下所示:

/*
KEY nu:10:2 // Example input document where 10 is the notify_id 2 is the user_id
{
    "somekey": "someValue"
}

KEY user_plus_ntfys:2 // Example output doc where "id": 2 is the user_id built from above
{
   "type": "user_plus_ntfys",
   "id": 2,
   "notifications" : [
     {"nid": 7, "doc": { "somekey": "someValue"}},
     {"nid": 9, "doc": { "somekey": "someValue"}},
     {"nid": 10, "doc": { "somekey": "someValue"}}
   ]
}
*/

function OnUpdate(doc, meta) {
    const MAX_RETRY = 16;
    const MAX_ARRAY = 3;
    
    // will process ALL data like nu:#:#
    var parts = meta.id.split(':');
    if (!parts || parts.length != 3 || parts[0] != "nu") return;
    var ntfy_id = parseInt(parts[1]);
    var user_id = parseInt(parts[2]);
    //log("Doc created/updated " +  meta.id + " ntfy_id " + ntfy_id  + " user_id " + user_id);

    var insert_json = {"nid": ntfy_id, doc};
    for (var tries=0; tries < 16; tries++) {
        var user_doc = addToNtfyArray(src_bkt, user_id, insert_json, MAX_ARRAY);
        if (user_doc == null) {
            // do nothing
            return;
        }
        var random_csum = user_doc.random;
        // this is a read write alias to the functons source bucket
        src_bkt["user_plus_ntfys:" + user_id] = user_doc;
        user_doc = src_bkt["user_plus_ntfys:" + user_id];
        if (random_csum !== user_doc.random) {
            // failure need to retry
            tries++;
        } else {
            // success could even delete the input notification doc here
            return;
        }
    }
    log ("FAILED to insert id: " + meta.id, doc)
}

function addToNtfyArray(src_bkt, user_id, insert_json, max_ary) {
    var ntfy_id = insert_json.nid;
    var random_csum;
    var user_doc = src_bkt["user_plus_ntfys:" + user_id];
    if (!user_doc) {
        // generate unique random #
        random_csum = Math.random();
        user_doc = { "type": "user_plus_ntfys", "id": user_id, "notifications" : [], "random": random_csum };
        user_doc.notifications.push(insert_json);
    } else {
        if (user_doc.notifications[0].nid >= ntfy_id && user_doc.notifications.length === max_ary) {
            // do nothing this is older data, we assume that nid always increases
            return null;
        } else {
            // find insert position
            for(var i=0; i<=user_doc.notifications.length + 1 ; i++) {
                if (i < user_doc.notifications.length && user_doc.notifications[i].nid === ntfy_id) {
                    // do nothing this is duplicate data we already have it, assume no updates to notifys
                    return null;
                }  
                if (i == user_doc.notifications.length || user_doc.notifications[i].nid > ntfy_id) {
                    // add to array middle or end
                    user_doc.notifications.splice(i, 0, insert_json);
                    random_csum = Math.random();
                    // update unique random #
                    user_doc.random = random_csum;
                    break;
                }
            }
        }
        while (user_doc.notifications.length > max_ary) {
            // ensure proper size
            user_doc.notifications.shift();
        }
    }
    return user_doc;
}

答案 1 :(得分:0)

可能有更好的数据建模方法。所有这些数据都需要放在单独的文档中吗?如果“ N”相对较小,则可以将所有这些都放入单个文档中的数组中。喜欢:

{
   "type": "user",
   "name": "ehsan",
   "notifications" : [
     {"somekey":"someValue"},
     {"somekey":"someValue"},
     {"somekey":"someValue"} 
   ]
}

然后该过程将是:

  1. 获取文档
  2. 将一条记录添加到通知数组
  3. 确定是否需要删除旧记录(然后将其删除)
  4. 保存更新的文档。

这种方法的优点是简单,不需要更新多个数据。您建模的方式可以起作用,但是您将需要ACID事务(Couchbase的Node SDK中尚不可用)或Eventing函数来检查以确保还没有每当创建新通知时,每个用户都会收到许多通知文档。