javascriptaws-lambdaamazon-dynamodbaws-sdk-jsaws-sdk-js-v3

AWS SDK JavaScript v3 / How to use ExpressionAttributeNames within dynamoDB Scan Command?


I'm using a Lambda function which gets me the user email from a user id within a dynamoDB table. I use the dynamoDB scan command to scan over all items within the dynamoDB table. I use the new v3 AWS JS SDK.

Question: Why does ExpressionAttributeNames not work properly in my case?

This works:

const params = {    
  FilterExpression: "user_info.user_id = :userid",  
  ExpressionAttributeValues: {
   ":userid": { S: user_id }
  },
  ProjectionExpression: "user_email",
  TableName: aws_table,
}

But this does NOT work, why?

const params = {
  FilterExpression: "#xyz = :userid",  
  ExpressionAttributeNames: {
    "#xyz": "user_info.user_id"  // <- filter does not work like this (returns 0 findings)
  },
  ExpressionAttributeValues: {
    ":userid": { S: user_id }
  },
  ProjectionExpression: "user_email",
  TableName: aws_table,
};

My Lambda scan operation code itself looks like:

const  { DynamoDBClient } = require("@aws-sdk/client-dynamodb");
const  { ScanCommand } = require("@aws-sdk/client-dynamodb");
const ddbClient = new DynamoDBClient({ region: aws_region });
...  

const run = async () => {
  try {
    const data = await ddbClient.send(new ScanCommand(params));
    data.Items.forEach(function (element, index, array) {
      console.log(element);
    });
    return data;
  } catch (err) {
    console.log("Error", err);
  }
}

await run();

npm i @aws-sdk/client-dynamodb

Documentation:

https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-dynamodb/interfaces/scancommandinput.html#expressionattributenames


Solution

  • This is the expected behaviour:

    DynamoDB interprets a dot in an expression attribute name as a character within an attribute's name

    // use multiple expression attribute names if you need a dynamic path:
    FilterExpression: "#user_info.#user_id = :userid"