How to fix 'The provided key element does not match the schema' error?

0

I want to get items that match one of the keys in an array using this code:

exports.handler = async (event) => {

    try {
        const IDs = 
        [
            {"profileID": {"S": "my_first_id"}}, 
            {"profileID": {"S": "my_second_id"}}
        ]

        const postsResult = await db.batchGetItem({
          RequestItems: {
            'Feed': {
              Keys: IDs
            }
          }
        }).promise();
        

        return {
            statusCode: 200,
            body: JSON.stringify(postsResult),
        };
    } catch (err) {
        console.log(err)
        return { error: err }
    }
}

But I am getting this error :

The provided key element does not match the schema

This is the schema:

type Feed @model @auth(rules: [{allow: private}]){
  profileID: String @index(name: "feedByProfileID")
  type: String
  postID: String
  shareID: String
  likeID: String
  commentID: String
  replyID: String
}
asked 10 months ago7961 views
1 Answer
1

My assumption is you are trying to do a BatchGetItem on a Global Secondary Index (GSI) which is not possible, this is because items in a GSI are not required to be unique, however, they are required to be unique for GetItem and BatchGetItem.

You can do one of 2 things:

  1. Send multiple Query calls
  2. Send a PartiQL ExecuteStatement call
// Declare function
const exStatement = statement => {
  db.executeStatement({
    Statement: statement
  })
    .promise() // Promise
    .then(res => {
      console.log(JSON.stringify(res)) 
    })
    .catch(err => console.log(err)) 
}

//Call function
exStatement(`SELECT * from "Feed"."feedByProfileID" where profileID IN ['my_first_id','my_second_id']`) // Up to 50 PK's
profile pictureAWS
EXPERT
answered 10 months ago
  • I tried PartiQL statement but the problem is that I need to order the items by date which seems to be impossible with PartiQL.

  • PartiQL orders the same way all other API's provide order, by the sort key. If you do not have date as your GSI sort key, you will need to re-create your index to include that.

  • Can I use the createdAt attribute which is generated automatically or I have to create my own attribute. This is my first time using DynamoDB so I still don't get its concepts clearly.

  • yes you can, you can use createdAt as the GSI Sort Key

  • type Feed @model @auth(rules: [{allow: private}]){ id: ID! @primaryKey(sortKeyFields: ["dateCreated"]) profileID: String @index(name: "feedByProfileID") dateCreated: AWSDateTime! } I reconstructed the model like this, but I still get this error "Must have at least one non-optional hash key condition in WHERE clause when using ORDER BY clause."

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions