0
0
DynamodbConceptBeginner · 3 min read

What is Set Type in DynamoDB: Explanation and Examples

In DynamoDB, a set type is a data type that stores multiple unique values of the same kind, such as strings, numbers, or binary data. It is useful for storing collections without duplicates, like tags or IDs, within a single attribute.
⚙️

How It Works

Think of a set type in DynamoDB like a basket that holds unique items of the same kind. For example, if you have a basket for apples, you can only put apples in it, and you cannot have two identical apples. Similarly, DynamoDB set types hold unique values of one data type: string, number, or binary.

This means if you try to add a duplicate value to a set, DynamoDB automatically ignores it, keeping only one copy. This helps when you want to store lists of things like user tags, unique IDs, or email addresses without worrying about duplicates.

There are three set types in DynamoDB: String Set (SS), Number Set (NS), and Binary Set (BS). Each set must contain only one type of data, and the order of items is not guaranteed.

💻

Example

This example shows how to create a DynamoDB item with a string set attribute representing user tags.

python
import boto3

dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('Users')

response = table.put_item(
    Item={
        'UserId': 'user123',
        'Tags': {'SS': ['sports', 'music', 'travel']}
    }
)

print('PutItem succeeded:', response)
Output
PutItem succeeded: {'ResponseMetadata': {'RequestId': '...', 'HTTPStatusCode': 200, ...}}
🎯

When to Use

Use set types in DynamoDB when you need to store a collection of unique values in a single attribute. This is helpful for:

  • Storing user interests or tags without duplicates.
  • Keeping track of unique IDs or codes related to an item.
  • Managing lists of email addresses or phone numbers where duplicates are not allowed.

Sets are efficient because DynamoDB handles uniqueness automatically, so you don't need extra code to check for duplicates.

Key Points

  • Set types store unique values of the same data type: string, number, or binary.
  • DynamoDB supports three set types: SS, NS, and BS.
  • Duplicates are automatically removed in sets.
  • Order of elements in a set is not guaranteed.
  • Sets are useful for attributes like tags, IDs, or unique lists.

Key Takeaways

DynamoDB set types store unique values of one data type in a single attribute.
Use string sets, number sets, or binary sets depending on your data.
Sets automatically prevent duplicate values without extra code.
Ideal for storing tags, unique IDs, or lists where duplicates are not allowed.