I'm attempting to retrieve an item from DynamoDB with a Lambda function and always get the same error:
ValidationException The provided key element does not match the schema
This is how I am currently attempting to pull the data. myAttribute
is not a string, as seen here. Since value
is a variable taken from queryStringParamters
, I am using the DocumentClient
which supports native JS types:
const AWS = require("aws-sdk")
const ddb = new AWS.DynamoDB.DocumentClient()
const getParams = {
TableName: "myTable",
Key: { myAttribute: value },
}
ddb.get(getParams, function(error, data) {
if (error)
{
console.log("get error", error)
}
else
{
console.log("get success", data)
}
})
Schema:
myTable:
Type: AWS::DynamoDB::Table
Properties:
TableName: myTable
AttributeDefinitions:
- AttributeName: myAttribute
AttributeType: S
- AttributeName: myOtherAttribute
AttributeType: S
KeySchema:
- AttributeName: myAttribute
KeyType: HASH
- AttributeName: myOtherAttribute
KeyType: RANGE
BillingMode: PAY_PER_REQUEST
Some of my alternative approaches attempted can be found below. They're all based on various implementations I've seen in the docs. I've tried combinations of what is listed below, but I'm only listing a few to give an idea of what I've tried without making the post too long. For example, below I mention that I've tried specifying the API version while using DocumentClient
. I've also attempted the same while not using the client.
Specifying apiVersion
, as seen here:
const ddb = new AWS.DynamoDB.DocumentClient({ apiVersion: "2015-03-31" })
Attribute as a string, as seen here:
const getParams = {
TableName: "myTable",
Key: { "myAttribute": value },
}
Not using DocumentClient
, and specifying S
in the Key
structure, as seen here:
const ddb = new AWS.DynamoDB({ apiVersion: "2015-03-31" })
const getParams = {
TableName: "myTable",
Key: { "myAttribute": { S: value } },
}
I'm not really sure how to proceed from here. I think I need to use DocumentClient
since it supports native JS types, but no matter what kind of Key
I use, the same error comes up. Any ideas on how to fix this?
CodePudding user response:
You're using the get
method of the Document Client, which maps to the underlying GetItem
API call. This API call requires the entire primary key to return the item. In your case, that means you would have to know the partition/hash and sort/range key of your item.
Since that's not the case as you mention in the comments, I suggest you use the Query
API. Query operates on item collections (all items that share a partition key) and allows you to return the whole item collection or filter in the item collection based on the sort key.