What is Set Type in DynamoDB: Explanation and Examples
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.
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)
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, andBS. - 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.