Couchbase中的条件Upsert

问题描述 投票:2回答:1

我有一些看起来像这样的文件:

{
"name": "n",
"age": 22
//other properties

"hash": "XyRZHDJJD6738..." //This property contains the hash of the object (calculated by the client)
}

从客户端,我应该是否:

  • 使用其键(已知)更新文档,仅在哈希不同的情况下(=>存储的对象和新的对象不相同)

  • 如果密钥不存在,则插入文档

[此操作是在相对较大的数据集上以批量模式完成的,并发访问=>因此,获取文档然后进行更新不是一种选择。

在Couchbase(5.1+)中可以做到这一点吗?

couchbase
1个回答
2
投票

通过调整文档模型,您可能会遇到类似这样的事情:

{
    "name": "n",
    "age": 22,
    "applied_hashes": {
        "XyRZHDJJD6738": null,
        "AB2343DCxdsAd": null,
        // ... other hashes
    }
}

现在,您可以将每个更新作为子文档操作来进行,第一个规范是尝试将更新的哈希插入到Applied_hashes中。如果该哈希/更新先前已应用,则此插入将失败,并且由于Sub-Document是原子的,因此不会对该文档进行任何更改。

使用Java SDK 3.x,它看起来像:

try {
  collection.mutateIn("id",
          Arrays.asList(
                  MutateInSpec.insert("applied_hashes.XyRZHDJJD6738", null).createPath(),
                  MutateInSpec.upsert("age", 24)
                  // .. other parts of update XyRZHDJJD6738 here
          ));
}
catch (PathExistsException err) {
  // Update XyRZHDJJD6738 has already been applied
  // No changes have been made to the document
}
© www.soinside.com 2019 - 2024. All rights reserved.