Search code examples
amazon-dynamodbboto3dynamodb-queries

DynamoDb Query and Append item to nested list inside a list, Python Boto3


I have this kind of entity in a dynamodb table:

{
   "fieldAA":152,
   "Big_List":[
      {
         "fieldA":"value",
         "Nested_List":[
            {
               "date":"29/09/2022"
            },
            {
               "date":"06/10/2022"
            },
            {
               "date":"04/11/2022"
            },
            {
               "date":"08/11/2022"
            }
         ]
      }
   ]
}
  1. How do I query(by entity id) the table in order to get the first date in the Nested_List? I have to do some comparison with the first date in the list

2.How to append a new date to the Nested_List?


Solution

  • You haven't provided much information, but this should be what you need.

    How do I query(by entity id) the table in order to get the first date in the Nested_List? I have to do some comparison with the first date in the list

    import boto3
    
    table_name = "test"
    dynamodb = boto3.client('dynamodb')
    table = dynamodb.Table(table_name)
    
    try:
        response = table.get_item(
            Key={
                'entity_id': '1235'
            },
            ProjectionExpression='#b.#n[0]',
            ExpressionAttributeNames={
                '#b': 'Big_List',
                '#n': 'Nested_List'
            }
        )
    
    except Exception as e:
        print(e)
    

    How to append a new date to the Nested_List?

    date = [{"date": "08/09/2023"}]
    
    try:
        table.update_item(
            Key={
                'entity_id': '1235'
            },
            UpdateExpression="SET #b.#n = list_append(#b.#n, :date)",
            ExpressionAttributeValues={":date": date},
            ExpressionAttributeNames={
                '#b': 'Big_List',
                '#n': 'Nested_List'
            }
        )
    except Exception as e:
        print(e)