Home > Back-end >  Query Dynamo DB with multiple columns using AWS SDK V3 and Typescript
Query Dynamo DB with multiple columns using AWS SDK V3 and Typescript

Time:01-25

I have the below piece of code that I try to use to fetch a row of data using values for 3 columns.

const client = new DynamoDB({region: "us-east-1"});
const params = {
TableName: Tables.TYPES,
ExpressionAttributeNames: {
    '#type': "type",
    '#region': "region",
    '#dock': "dock"
},
ExpressionAttributeValues: {
    ":type": type,
    ":dock": dock,
    ":region": region
 },
 KeyConditionExpression: '#type = :type AND #dock = :dock AND #region = :region'
 }
 let types: Record<string, NativeAttributeValue> = data = await client.send(new QueryCommand(params));
 console.log("Received data ", data);

However when I run the above code I get the following error.

"errorMessage": "Cannot read properties of undefined (reading '0')"

What am I doing wrong here? How can I read the row using values for multiple columns in my Dynamo DB table? I am using @aws-sdk/client-dynamodb by the way. Appreciate any help.

UPDATE: Still not working:

const params = {
            TableName: Tables. TYPES,
            FilterExpression: 'type = :type AND dock = :dock AND region = :region',
            ExpressionAttributeValues: {
                ":type": {S: type},
                ":dock": {S: dock},
                ":region": {s: region}
            }
        }

CodePudding user response:

KeyConditionExpression is for keys only, your partition key and sort key. Outside of that, if you wish to filter on non key attributes you must use FilterExpression.

Assuming type is your Partition key, the params would look like this (edit further to suit your specific needs):

const params = {
TableName: Tables.TYPES,
ExpressionAttributeNames: {
    '#type': "type",
    '#region': "region",
    '#dock': "dock"
},
ExpressionAttributeValues: {
    ":type": type,
    ":dock": dock,
    ":region": region
 },
 KeyConditionExpression: "#type = :type",
 FilterExpression: "#dock = :dock AND #region = :region"
 }
  • Related