4

I have a DynamoDB table that contains primary key : userID, sort key : sessionID and another column which is named examID.

i would like to return a list that returns all records that have the userID and examID sent by me. Here is my code:

export const main = handler(async (event, context) => {

  const data = JSON.parse(event.body);
  const params = {
    TableName: process.env.tableNameExamResults,
    KeyConditionExpression: "userId = :userId and examId = :examId",
    ExpressionAttributeValues: {
      ":userId": event.requestContext.identity.cognitoIdentityId,
      ":examId": data.examId

    }
  };

  const result = await dynamoDb.query(params);

  
  return result.Items;
});


this is the error that i get: { "statusCode": 500, "body": "{"error":"Query condition missed key schema element: sessionId"}",

...

I think that maybe i should include a Filter Expression or not sure if i have to recreate the DB with an index.

Any help is appreciated. thank you

Etika49
  • 680
  • 1
  • 8
  • 16
  • i thought about querying based on userId , getting all sessionId and then filter by examID with FilterExpression. Not sure how to implement this exactly. Docu is kind of unclear to me ... https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html#query-property – Etika49 Sep 07 '20 at 14:44

1 Answers1

1

i just added a new GSI and then i also edited my code :

const params = {
    TableName: process.env.tableNameExamResults,
    IndexName: 'userId-examId-index', 
    KeyConditionExpression: "userId = :userId and examId = :examId",
    ExpressionAttributeValues: {
      ":userId": event.requestContext.identity.cognitoIdentityId,
      ":examId": data.examId

    }
  };

This seems to work now.

Etika49
  • 680
  • 1
  • 8
  • 16
  • 1
    creating a new index will create a new table , thus adding more cost. I would suggest pull data using projection if every user has few examIds. – Mr Nobody Sep 12 '20 at 12:33