How to create multiple DynamoDB entries under the same primary key?

Viewed 11074

I am developing a skill for Amazon Alexa and I'm using DynamoDB for storing information about the users favorite objects. I would like 3 columns in the database:

  1. Alexa userId
  2. Object
  3. Color

I currently have the Alexa userId as the primary key. The problem that I am running into is that if I try to add an entry into the db with the same userId, it overwrites the entry already in there. How can I allow a user to have multiple objects associated with them in the db by having multiple rows? I want to be able to query the db by the userId and receive all the objects that they have specified.

If I create a unique id for every entry, and there are multiple users, I can't possibly know the id to query by to get the active users' objects.

5 Answers

You can use a sort key, so for example you can have AlexaUserID as your primary key, and than Object as your sort key.

Than if you want to query all the users that have the same AlexaUserID you can use the Query API for DynamoDB. (This is important because get_item() wont work, because for that you have to provide both primary key and also the sort key).

For example;

import boto3
from boto3.dynamodb.conditions import Key

client = boto3.resource('dynamodb')
table = client.Table('yourCoolTableName')

let userName = "thisIsMyAlexaUserName"

response = table.query(
     KeyConditionExpression=Key('AlexaUserID').eq(userName)
)    

items = response['Items']

You can read more about the Query API here, also here is the example from AWS's own documentation.

Related