简体   繁体   中英

Creating a 'SS' item in DynamoDB using boto3

I'm trying to create an item in AWS DynamoDB using boto3 and regardless what I try I can't manage to get an item of type 'SS' created. Here's my code:

client = boto3.resource('dynamodb', region_name=region)
table = client.Table(config[region]['table'])
sched = {
    "begintime": begintime,
    "description": description,
    "endtime": endtime,
    "name": name,
    "type": "period",
    "weekdays": [weekdays]
}
table.put_item(Item=sched)

The other columns work fine but regardless what I try, weekdays always ends up as a 'S' type. For reference, this is what one of the other items look like from the same table:

{'begintime': '09:00', 'endtime': '18:00', 'description': 'Office hours', 'weekdays': {'mon-fri'}, 'name': 'office-hours', 'type': 'period'}

Trying to convert this to a Python structure obviously fails so I'm not sure how it's possible to insert a new item.

To indicate an attribute of type SS (String Set) using the boto3 DynamoDB resource-level methods, you need to supply a set rather than a simple list. For example:

import boto3

res = boto3.resource('dynamodb', region_name=region)

table = res.Table(config[region]['table'])

sched = {
    "begintime": '09:00',
    "description": 'Hello there',
    "endtime": '14:00',
    "name": 'james',
    "type": "period",
    "weekdays": set(['mon', 'wed', 'fri'])
}

table.put_item(Item=sched)

As follow up on @jarmod's answer:

If you want to call update_item with a String Set, then you'll insert a set via ExpressionAttributeValues property like shown below:

entry = table.put_item(
    ExpressionAttributeNames={
        "#begintime": "begintime",
        "#description": "description",
        "#endtime": "endtime",
        "#name": "name",
        "#type": "type",
        "#weekdays": "weekdays"
    },
    ExpressionAttributeValues={
        ":begintime": '09:00',
        ":description": 'Hello there',
        ":endtime": '14:00',
        ":name": 'james',
        ":type": "period",
        ":weekdays": set(['mon', 'wed', 'fri'])
    },
    UpdateExpression="""
        SET #begintime= :begintime,
        #description = :description,
        #endtime = :endtime,
        #name = :name,
        #type = :type,
        #weekdays = :weekdays
        """
)

(Hint: Usage of AttributeUpdates (related Item s equivalent for put_item calls) is deprecated, therefore I recommend using ExpressionAttributeNames , ExpressionAttributeValues and UpdateExpression ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM