代码之家  ›  专栏  ›  技术社区  ›  夏期劇場

DynamoDB:如何将值附加到现有项的列表(数组)中

  •  0
  • 夏期劇場  · 技术社区  · 6 年前

    (我正在使用AWS PHP SDK)

    假设我有一张桌子:

    Table name: article
    Primary partition key: article_id (Number)
    

    带着一个 手动 创建的项目:

    {
        "article_id": 10010,
        "updated": "2018-02-22T20:15:19.28800Z",
        "comments": [ "Nice article!", "Thank you!" ]
    }
    

    添加新评论:

    我知道如何通过以下方式完全更新(覆盖)现有项目:

    $key = $marshaler->marshalJson('
        {
            "article_id": 10010
        }
    ');
    
    $eav = $marshaler->marshalJson('
        {
            ":u": "2018-02-22T20:15:19.28800Z",
            ":c": [ "Nice article!", "Thank you!", "This is the new one!" ]
        }
    ');
    
    $params = [
        'TableName' => 'article',
        'Key' => $key,
        'ExpressionAttributeValues'=> $eav,
        'UpdateExpression' => 'set updated=:u, comments=:c',
        'ReturnValues' => 'UPDATED_NEW'
    ];
    

    我可以以某种方式附加新值(aka) 添加新评论 这边但这实际上仍然在重新创建整个项目,这不是我喜欢的方式。

    我如何简单地将新值添加到现有项中的列表/数组中?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Andi    6 年前

    Add elements to the list

    使用SET更新列表元素时,该元素的内容将替换为指定的新数据。如果元素不存在,SET会将新元素追加到列表的末尾。

    创建表格

    aws dynamodb create-table \
        --table-name article \
        --attribute-definitions AttributeName=article_id,AttributeType=N \
        --key-schema AttributeName=article_id,KeyType=HASH \
        --provisioned-throughput ReadCapacityUnits=1,WriteCapacityUnits=1
    

    添加项

    aws dynamodb put-item  \
            --table-name article \
            --item '{
                "article_id": {"N": "123"},
                "updated": {"S": "00:00:00"},
                "comments": {
                      "L": [
                        { "S": "Nice article!" },
                        { "S": "Thank you!" }
                    ]}
              }'
    

    更新项目

    aws dynamodb update-item \
        --table-name article \
        --key '{"article_id":{"N":"123"}}' \
        --update-expression "SET comments[50] = :c, updated=:u" \
        --expression-attribute-values '{
            ":u": {"S": "01:01:01"},
            ":c": {"S": "This is the new one!"}
          }' \
        --return-values ALL_NEW
    

    列表 comments[] 在更新之前包含两个元素(索引0和1)。像 comments[50] 如果不存在,则SET操作会将其附加到列表的末尾( comments[2] ).

    推荐文章