Insem 1: DynamoDB Answers
User.uid
User.password
User.email
Question.question_text
Question.timestamp
Question.uid
Answer.question_text
Answer.answer_seq_no
Answer.answer_text
Answer.timestamp
Answer.uid
- User subscribing to one or more topics
- User voting 👍 or 👎 for an answer
Answer.upvotes
Answer.downvotes
- List Users who are subscribed to a give topic
Subscriptions.uid
Subscriptions.topic
Q1. Provide key-value DB design
Users {
uid: HASH,
password,
email,
}
Questions {
uid: HASH,
question_text: RANGE,
timestamp,
}
Answers {
question_text: HASH,
answer_seq_no: RANGE,
answer_text,
timestamp,
downvotes,
upvotes,
uid,
upvotes-index: LocalSecondaryIndex {
question_text: HASH,
upvotes: RANGE,
},
uid-index: GlobalSecondaryIndex {
uid: HASH,
},
}
Subscriptions {
topic: HASH,
uid: RANGE,
}
Q2. Provide code for performing each of the above database operations.
- Registers on the site
table = dynamodb.Table("Users")
item = {
"uid": uid,
"password": password,
"email": email
}
table.put_item(Item=item)
- Post a question
table = dynamodb.Table("Questions")
item = {
"question_text": question_text,
"timestamp": timestamp,
"uid": uid
}
table.put_item(Item=item)
- Post Answer
table = dynamodb.Table("Answers")
item = {
"question_text": question_text,
"answer_seq_no": answer_seq_no,
"answer_text": answer_text,
"timestamp": timestamp,
"uid": uid,
"upvotes": 0,
"downvotes": 0
}
table.put_item(Item=item)
- User subscribing to one or more topics
table = dynamodb.Table("Subscriptions")
item = {
"uid": uid,
"topic": topic
}
table.put_item(Item=item)
- User voting 👍 or 👎 for an answer
table = dynamodb.Table("Answers")
table.update_item(
Key={
"question_text": question_text,
"answer_seq_no": answer_seq_no
},
UpdateExpression="ADD upvotes :upvoted, downvotes :downvoted",
ExpressionAttributeValues={
":upvoted": upvoted,
":downvoted": downvoted
}
)
- List all questions posted by a User
table = dynamodb.Table("Questions")
resp = table.query(
KeyConditionExpression="uid = :uid",
ExpressionAttributeValues={
":uid": uid
}
)
- List all answers for a given "question_text"
table = dynamodb.Table("Answers")
table.query(
IndexName="upvotes-index",
KeyConditionExpression="question_text = :question_text",
ScanIndexForward=False,
ExpressionAttributeValues={
":question_text": question_text
}
)
- List all answers for a given uid
table = dynamodb.Table("Answers")
table.query(
IndexName="uid-index",
KeyConditionExpression="uid = :uid",
ExpressionAttributeValues={
":uid": "four"
}
)
- List all answers for a given uid having ThumpsUp >= 10
table = dynamodb.Table("Answers")
table.query(
IndexName="uid-index",
KeyConditionExpression="uid = :uid",
FilterExpression="upvotes >= :limit",
ExpressionAttributeValues={
":uid": "four",
":limit": 10
}
)
- List users who are subscribed to a given topic
table = dynamodb.Table("Subscriptions")
table.query(
KeyConditionExpression="topic = :topic",
ExpressionAttributeValues={
":topic": "typescript"
}
)