Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use begins_with in AWS DynamoDb js sdk?

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.

enter image description here enter image description here

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

like image 334
Ani Avatar asked Dec 05 '19 10:12

Ani


Video Answer


1 Answers

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"
  }
}
like image 90
uday8486 Avatar answered Oct 25 '22 14:10

uday8486