Question:
DynamoDB tables with a primary key that is a composite hash-range key are unique. Does this extend to secondary indices too?
Example:
I have a comments DynamoDB table with a post_id primary key and comment_id range key. Additionally there's a local secondary index with a date-user_id range key.
Each entry is a comment a user has left on post. The purpose of the secondary index is to count how many unique users left a comment on a post on a specific day.
Entry 1: post_id: 1 comment_id: 1 date-user_id: 2014_06_24-1
Entry 2: post_id: 1 comment_id: 2 date-user_id: 2014_06_24-1
Entry 3: post_id: 1 comment_id: 3 date-user_id: 2014_06_24-2
When I do a query specifying the secondary index, and pass in a condition of post_id equals 1 and a date-user_id equals 2014_06_24-1, I'm getting a count of 2 and I'm expecting a count of 1.
Why does the secondary index have two entries with the same primary key/range key.
In DynamoDB, each record in a table is uniquely identified by the primary key for your table. You can use this primary key to ensure there is not an existing record with the same primary key. To do so, you would use a Condition Expression to prevent writing an item if an item with the same key already exists.
Each table in DynamoDB can have up to 20 global secondary indexes (default quota) and 5 local secondary indexes. For more information about the differences between global secondary indexes and local secondary indexes, see Improving data access with secondary indexes.
To define a unique constraint for the username too, just add items with the type “username”. Also, by defining the rarer of the two parts of the key as the partition, you'll end up with more partitions, which is a best practice when working with DynamoDB.
A global secondary index lets you query over the entire table, across all partitions. A local secondary index lets you query over a single partition, as specified by the partition key value in the query. Queries on global secondary indexes support eventual consistency only.
Secondary indexes don't guarantee uniqueness. From the docs:
In addition, remember that global secondary indexes do not enforce uniqueness
http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GuidelinesForTables.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With