On my website I have a form with the fields: full name, email, phone #, and message (image below).
After someone fills out the form, I want to query my table to see if there are any items with the same email address, or phone # that the user gave to the form. If there IS an item with the same email/phone # then I want to retrieve that item’s "sharedID", then create a new item in the table with the submitted form information as well as the retrieved id.
Currently, I’m performing a dynamoDB query to achieve this (code below). However, I believe that I need to include the primary key (id) in the query. However, this is a problem because there’s no way of knowing an item’s id when querying (being that the id’s are randomly generated).
const checkForSameEmailOrPhone = () => {
const params = {
TableName: "customers",
ProjectionExpression: "sharedID",
FilterExpression: "email_address = :givenEmail or phone_number = :givenNumber",
ExpressionAttributeValues: {
":givenEmail": "[email protected]",
":givenNumber": '7777777'
}
};
docClient.query(params, function(err, data){
if (err) {
console.error('Error in GetItem', err);
} else {
console.log('data', data);
function createItem() {
const uniqueId = nanoid();
let params = {
TableName :"customers",
ConditionExpression: "attribute_not_exists(z)",
Item:{
"id": uniqueId,
"email_address": "[email protected]",
"full_name": "a name",
"phone_number": "822222222",
"message": "different",
"sharedId": data?.Items[0]?.id || uniqueId
}
};
docClient.put(params, function(err, data) {
if (err) {
console.error('sdk ERROR', err);
} else {
console.log('success');
}
});
};
createItem();
}
});
};
That being said, I was wondering if anyone could help me find a cost effective/efficient solution to retrieve the id of an item which contains the same email and phone # the user gave on the form.
CodePudding user response:
You should create Global Secondary Indexes and use the fields that you want to query by as partition keys. You can have multiple GSI for a table and the best practice is to add only the necessary fields to the index (so you use less read capacity units when querying the data). You can read more about the indexes in the official documentation