【问题标题】:Dynamically and conditionally update_item on nested DynamoDB dict在嵌套的 DynamoDB dict 上动态和有条件地 update_item
【发布时间】:2020-01-03 19:31:17
【问题描述】:

我有一个 DynamoDB 表,其中包含以下格式的项目:

{
  "attributes": {
    "cities": {
      "oakland": {
        "data": "Some stuff."
      }
    },
    "people": {
      "Joe": {
        "data": "Some stuff."
      }
    }
}

我有一个 JSON 文件 (dynamodbupdate.json),其中包含我要添加的新数据。结构如下:

{
  "attributes": {
    "cities": {
      "oakland": {
        "data_point_1": "warm"
      }
    },
    "people": {
      "Joe": {
        "data_point_1": "tall",
        "data_point_1": "smart"
      }
    }
}

我想使用 boto3 库中的 update_item 操作更新表,以便在不覆盖现有数据的情况下将新数据添加到我的表中。我可以使用单个表项执行此操作,但我正在尝试找到一种方法将新数据动态添加到多个项中,以便我的新表如下所示:

{
  "attributes": {
    "cities": {
      "oakland": {
        "data": "Some stuff.",
        "data_point_1": "warm"
      }
    },
    "people": {
      "Joe": {
        "data": "Some stuff."
        "data_point_1": "tall",
        "data_point_2": "smart"
      }
    }
}

对单个项目执行此操作的 UpdateExpression 如下所示:

UpdateExpression = 'SET people.Joe.data_point_1 = if_not_exists(people.Joe.data_point_1, tall)'

但是,我很想找到一种方法来遍历 dynamodbupdate.json 文件的全部内容并为所有数据发出 update_item 命令。

This post 非常接近我的需要,但在我的示例中,我无法理解正确的方法。感谢您的帮助!

【问题讨论】:

    标签: python python-3.x amazon-dynamodb


    【解决方案1】:

    我能够(大部分)通过执行以下操作来解决这个问题:

    def lambda_handler(event, context):
        configPath = os.environ['LAMBDA_TASK_ROOT'] + "/dynamodbupdate.json"
        configContents = open(configPath).read()
        configJson = json.loads(configContents)
        ld = configJson.get('attributes').get('cities')
        cities_dict = (list(ld))
        for x in cities_dict:
            all_dp = list(ld.get(x))
            for dp in all_dp:
                update_query = 'SET #a.#c.#x.#dp = if_not_exists(#a.#c.#x.#dp, :val)'
                perform_update = table.update_item(
                    Key={'primarykey': whateveryourkeyis},
                    ExpressionAttributeValues={
                        ':val': ld.get(x).get(dp)
                    },
                    ExpressionAttributeNames={
                        '#a': 'attributes',
                        '#c': 'cities',
                        '#x': x,
                        '#dp': dp
                    },
                    UpdateExpression=update_query)
    

    我也可以遍历城市/人口级别并提取数据。希望这对某人有帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多