gpt4 book ai didi

amazon-dynamodb - DynamoDB - 如果哈希(或哈希和范围组合)不存在则放置项目

转载 作者:行者123 更新时间:2023-12-02 01:43:45 26 4
gpt4 key购买 nike

以下是我的用例:我有一个带有哈希 + 范围键的 Dynamo 表。当我将新项目放入表中时,我想进行唯一性检查。有时我想保证哈希值是唯一的(忽略范围)。其他时候我想允许重复的哈希值,但保证哈希值和范围的组合是唯一的。我怎样才能做到这一点?

我尝试了 attribute_not_exists。它似乎处理第二种情况,它检查哈希+键组合。这是一个 PHP 示例:

$client->putItem(array(
'TableName' => 'test',
'Item' => array(
'hash' => array('S' => 'abcdefg'),
'range' => array('S' => 'some other value'),
'whatever' => array('N' => 233)
),
'ConditionExpression' => 'attribute_not_exists(hash)'
));

奇怪的是,如果我使用 attribute_not_exists(hash)attribute_not_exists(range) 似乎并不重要。他们似乎都在做同样的事情。这是它应该如何工作的吗?

知道如何处理我只想检查哈希的唯一性的情况吗?

最佳答案

你不能。 DynamoDB 中的所有项目均按其哈希哈希+范围(取决于您的表)建立索引。

对迄今为止发生的事情的总结:

  • 单个散列键可以有多个范围键。
  • 每个项目都有一个哈希和一个范围
  • 您正在发出 PutItem 请求,并且必须提供哈希范围
  • 您在 hashrange 属性名称上提供带有 attribute_not_existsConditionExpression
  • attribute_not_exists 条件只是检查具有该名称的属性是否存在,它不关心值

让我们来看一个示例。让我们从包含以下数据的 hash+range 键表开始:

  1. 哈希=A,范围=1
  2. 哈希=A,范围=2

有四种可能的情况:

  1. 如果您尝试使用 hash=A,range=3attribute_not_exists(hash) 放置项目,PutItem将会成功,因为 attribute_not_exists(hash) 的计算结果为 true。不存在键 hash=A,range=3 满足 attribute_not_exists(hash) 条件的项目。

  2. 如果您尝试使用 hash=A,range=3attribute_not_exists(range) 放置项目,PutItem将会成功,因为 attribute_not_exists(range) 的计算结果为 true。不存在键 hash=A,range=3 满足 attribute_not_exists(range) 条件的项目。

  3. 如果您尝试使用 hash=A,range=1attribute_not_exists(hash) 放置项目,PutItem将会失败,因为 attribute_not_exists(hash) 的计算结果为 false。存在键 hash=A,range=1 的项目,但不满足 attribute_not_exists(hash) 条件。

  4. 如果您尝试使用 hash=A,range=1attribute_not_exists(range) 放置项目,PutItem将会失败,因为 attribute_not_exists(range) 的计算结果为 false。存在键 hash=A,range=1 的项目,但不满足 attribute_not_exists(range) 条件。

这意味着将会发生以下两种情况之一:

  1. 数据库中存在哈希+范围对。
    • attribute_not_exists(hash) 必须为 true
    • attribute_not_exists(range) 必须为 true
  2. 数据库中不存在哈希+范围对。
    • attribute_not_exists(hash) 必须为 false
    • attribute_not_exists(range) 必须为 false

在这两种情况下,无论将其放在散列键还是范围键上,都会得到相同的结果。 hash+range 键标识整个表中的单个项目,并且正在针对该项目评估您的条件。

您正在有效地执行“如果具有此哈希+范围键的项目尚不存在,则放置此项目”。 p>

关于amazon-dynamodb - DynamoDB - 如果哈希(或哈希和范围组合)不存在则放置项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32833351/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com