Philip Kirkbride
Philip Kirkbride

Reputation: 22879

DynamoDB Scan get attribute of object on nodejs

I'm currently getting all entries in my database using the following:

const params = {        
    TableName: process.env.AWS_DYNAMODB_TABLE,
    Select: "SPECIFIC_ATTRIBUTES",  
    AttributesToGet: ["SessionValue"]                                                                                                                                             
};           
                                
dynamoClient.scan(params, function(err, data) {
    console.log("GetItem succeeded:", JSON.stringify(data, null, 2));
});

The problem is I don't need everything in SessionValue which is a very large object. Instead I want to do something like:

const params = {        
    TableName: process.env.AWS_DYNAMODB_TABLE,
    Select: "SPECIFIC_ATTRIBUTES",  
    AttributesToGet: ["SessionValue.wallet.keys"]                                                                                                                                             
};

However running the above doesn't return anything. Is this possible with DynamoDb on nodejs?

Upvotes: 2

Views: 2492

Answers (1)

geekmuse
geekmuse

Reputation: 425

You can do this with a Projection Expression.

var AWS = require('aws-sdk');
var dynamoClient = new AWS.DynamoDB.DocumentClient();

const params = {        
    TableName: process.env.AWS_DYNAMODB_TABLE,
    ExpressionAttributeNames: {
        "#S": "SessionValue",
        "#w": "wallet",
        "#k": "keys",
    },
    Select: "SPECIFIC_ATTRIBUTES",
    ProjectionExpression: "#S.#w.#k",                                                                                                                                        
};

dynamoClient.scan(params, function(err, data) {
    if (err) {
        console.log(err, err.stack);
    } else {
        console.log("GetItem succeeded:", JSON.stringify(data, null, 2));
    }
});

It's probably important to note that the response includes the full object envelope, so you'll have to unwrap it in your success callback (if you were perhaps hoping that the Scan call would just return only the nested items). An example response from a mocked table is below.

GetItem succeeded: {
  "Items": [
    {
      "SessionValue": {
        "wallet": {
          "keys": [
            "brad001",
            "brad002"
          ]
        }
      }
    },
    {
      "SessionValue": {
        "wallet": {
          "keys": [
            "foo001",
            "foo002"
          ]
        }
      }
    }
  ],
  "Count": 2,
  "ScannedCount": 2
}

Upvotes: 3

Related Questions