Search code examples
node.jsaws-lambdaaws-step-functionsdynamodb-queries

Aws Lambda to read the user input dynamically and return the data from Dynamo table


Lambda provides the expected result only when I pass the value manually (Id = '011010').

In the step function the value "ID" value will be random based on the logic from previous step, since the Id value is not static how to handle this scenario "ExpressionAttributeValues"

I tried all the below syntax but no luck..

ExpressionAttributeValues: { ':value':  $.External.Id}   
ExpressionAttributeValues: { ':value':  External.Id.$}   
ExpressionAttributeValues: { ':value':  $.Id}   
ExpressionAttributeValues: { ':value':  Id.$}   
ExpressionAttributeValues: { ':value':  event.Id}

Lambda-Code

   'use strict'
const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient();

 
var params = {
 TableName: 'temptable',
 IndexName: 'Id-CurrentStatus-index',
 KeyConditionExpression: '#Id= :value',
 ExpressionAttributeNames: { '#Id': 'Id'},
 ExpressionAttributeValues: { ':value': 'M1' }
       
};

async function queryItems(){
 try {
   const data = await docClient.query(params).promise()
   return data
 } catch (err) {
   return err
 }
}

exports.handler = async (event, context) => {
 try {
   const data = await queryItems()
   return { body: JSON.stringify(data) }
 } catch (err) {
   return { error: err }
 }
}

I can read it from the

   console.log("Memberid :" + JSON.stringify(event.Id, null, 2))

but how to pass the same value in the

    ExpressionAttributeValues: { ':value': 'M1' } 

I tried the below syntax. nothing works

    ExpressionAttributeValues: { ':value': JSON.stringify(event.Id, null, 2) }
    ExpressionAttributeValues: { ':value': event.Id}
    ExpressionAttributeValues: { ':value': event.Id}
    ExpressionAttributeValues: { ':value': Id} 

Solution

  • I got the required code after checking multiple thread.

    AWS Lambda function to scan/query DynamoDB table using array values as FilterExpression

    'use strict'
    
    var AWS = require('aws-sdk');
    var mydocumentClient = new AWS.DynamoDB.DocumentClient();
    
    exports.handler = function (event, context, callback) {
    
        var params = {
            TableName: 'temptable',
            KeyConditionExpression : 'Id= :Id',
            FilterExpression : 'Id in (:Id)',
                ExpressionAttributeValues: {
                ":Id": event.Id
            }
    
        };
        
          
          mydocumentClient.scan(params, function (err, data){
            if (err) {
                callback(err, null);
            }else{
              callback(null, data);
            }
        })
    
    }