I have a use case to apply begins_with on the primary sort key of an AWS Dynamodb table,
I am able to query the table using begins_with key condition from the AWS Console,
I wish to achieve the same using the AWS Javascript SDK.
I have the following fields in my table -
1. user_id (Primary partition key)
2. user_relation (Primary sort key)
I tried the following code -
let AWS = require('aws-sdk');
let util = require('util');
AWS.config.update({
region: 'us-east-1'
});
let connection = new AWS.DynamoDB.DocumentClient();
let params = {
TableName: 'user_details',
KeyConditionExpression: 'user_id = :user_id and user_relation begins_with :user_relation',
ExpressionAttributeValues: {
':user_id': "1234",
':user_relation': "followed-by"
}
};
console.log('getQuery Params => ', params);
let dynamoDb = util.promisify(connection.query).bind(connection);
let results = await dynamoDb(params);
console.log('results => ', results);
I am getting a syntax error, what is the correct way to use begins_with while querying an AWS DynamoDb table?
Error -
(node:40474) UnhandledPromiseRejectionWarning: ValidationException: Invalid KeyConditionExpression: Syntax error; token: "begins_with", near: "user_relation BE
GINS_WITH :user_relation"
References -
https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#query-property
DynamoDB,how to query with BEGINS_WITH
Can't Query DynamoDB with Begins_with for list of Items
Try :
const params = {
TableName: 'user_details',
KeyConditionExpression: '#user_id = :user_id and begins_with(#user_relation, :user_relation)',
ExpressionAttributeNames:{
"#user_id": "user_id",
"#user_relation": 'user_relation'
},
ExpressionAttributeValues: {
":user_id": "1234",
":user_relation": "followed-by"
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With