首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >基于属性更新每个Dynamodb项的有效方法

问基于属性更新每个Dynamodb项的有效方法
EN

Stack Overflow用户
提问于 2019-02-01 18:57:35
回答 1查看 614关注 0票数 1

我们有一个包含大约8,000条记录的DynamoDB表,我们需要对每条记录进行更新。每个记录的结构都类似于:id: 1492357, appIds: [123232], info: "{stringified json}",我们想要做的是将" appIds“数组插入到"info”的紧张的json值中,这样如果我们解析json,appIds属性现在是json中的一个属性。

我们有一个API,它将通过调用myApi/:id/update为我们实现这一点,并有一个shell脚本,它将从dynamo获取表中每个记录的id。我们只需循环id数组,并使用每个id来压缩api,但这似乎效率低下。

在Dynamo中是否有一种本地的方法来做这样的事情(绕过api)?我对脚本或curl也不太熟悉,如果没有一种本地的方法,是否有一种更有效的方法来循环我们的ids数组并为每个ids调用api?我们根本不关心api响应,只关心它是否有200个响应。

当前脚本:

代码语言:javascript
复制
#!/bin/bash

records=`aws dynamodb scan --table-name myTable --attributes-to-get '["id"]' | jq '.'`
count=$(jq '.Count' <<< "${records}")
ids=$(jq -r '.Items | .[] | {id: .id.S} | @base64' <<< "${records}")

echo ========== fetched $count records =========
for id in $ids; do
  _jq() {
    echo ${id} | base64 --decode | jq -r ${1}
  }
  userId=$(_jq '.id')
  url=$(curl myApi/${userId}/update)
  echo $userId :
done
EN

回答 1

Stack Overflow用户

发布于 2022-09-19 11:24:57

我有一个类似于你的bash脚本。我可以用bash读取dynamoDB的记录。然后,我有了另一个python脚本,它在dynamodb数据库中上传条目。您可以做的是在for循环中调用python脚本并向其发送相关的参数。

巴什:

​

代码语言:javascript
复制
for item in "${table_data[@]}"; do
  argument1=$(jq '.argument1' <<< "$item")
  argument2=$(jq '.argument2' <<< "$item")
  argument3=$(jq '.argument3' <<< "$item")
  key = $(jq '.key' <<< "$item")
  sortkey = $(jq '.sortkey' <<< "$item")

  python3 cli.py update-dynamo-table --key $key --sortkey $sortkey \
                        --argument1 $argument1 \
                        --argument2 $argument2 \
                        --argument3 $argument3  #  > /dev/null 2>&1 &  Uncomment no to see the outputs of the python command

  echo "DynamoDB item updated correclty"

​

Python:

​

代码语言:javascript
复制
import click
import sys
import os
import boto3

## Connecting to aws profile, boto3, dynamoDB table
aws_profile = os.environ.get('AWS_PROFILE')
aws_region = os.environ.get('AWS_REGION')
click.echo(f"Using profile {aws_profile} and region {aws_region}" )
session = boto3.session.Session(profile_name=aws_profile)
dynamodb = boto3.resource('dynamodb', region_name=aws_region)
table = dynamodb.Table('Name-of-dynamodb-table')

@click.group()
    def updateCommand():
    pass

@updateCommand.command()
@click.option('--key',  help='Primary Key of item on dynamoDB.')
@click.option('--sortkey',  help='Sort key of item on dynamoDB.')
@click.option('--argument1',  help='Value of argument1 to update on dynamoDB.')
@click.option('--argument2',  help='Value of argument2 to update on dynamoDB.')
@click.option('--argument3',  help='Value of argument3 to update on dynamoDB.')
## Declaration of function to update a table in DynamoDB.
## This function checks that the table exists annd if exists it updates the corresponding attributes.
def update_dynamo_table(key, sortkey, argument1, argument2, argument3):
    """Update an entry in dynamoDB table"""
    
    ## Validate that the item to update is actually in your dynamodb table
    response = pii_non_pii_table.get_item(
            Key={
                'key' : key,
                'sortkey' : sortkey
            }
        )
                
    if 'Item' not in response:
        click.echo("Item with specified keys does not exist, create it instead.")
        return None

    ## Table update
    ## Update expression string formation
    updateExpression = "set "
    expressionAttributeValues = {}
    expressionAttributeNames = {}

    if argument1 is not None :
        updateExpression += '#argument1=:argument1,'
        expressionAttributeNames['#argument1'] = "argument1"
        expressionAttributeValues[':argument1'] = argument1
    
    if argument2 is not None :
        updateExpression += '#argument2=:argument2,'
        expressionAttributeNames['#argument2'] = "argument2"
        expressionAttributeValues[':argument2'] = argument2
    
    if argument3 is not None :
        updateExpression += '#argument3=:argument3,'
        expressionAttributeNames['#argument3'] = "argument3"
        expressionAttributeValues[':argument3'] = argument3

    updateExpression = updateExpression[:-1]

    click.echo(updateExpression)
    click.echo(expressionAttributeValues)

    response = table.update_item(
        Key={
            'key': key,
            'sortkey': sortkey 
        },
        UpdateExpression=updateExpression,
        ExpressionAttributeNames=expressionAttributeNames,
        ExpressionAttributeValues=expressionAttributeValues,
        ReturnValues="UPDATED_NEW"
    )
    ## return response
    ## Output message.
    click.echo(f"Table UPDATED correctly.")

if __name__ == '__main__':
    updateCommand()

​

如果这有帮助,请告诉我!!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54485638

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档