How to get nested items in dynamodb?

608 views Asked by At

I m using node typescript and local dynamodb. I'm unable to get a specific nested document. I m trying to get a post on the basis of id. I m using email as pk.Here is the dynamodb table

let params1:any= {
      TableName: "userTable",
      // Key: {
      //   email: event.body.email

      // },
      FilterExpression: "#posts[0].#id = :postId",
       // KeyConditionExpression: `#postId= :postId`,
      ExpressionAttributeNames: {
        "#posts": "posts",
        "#id": "id",

      },
      ExpressionAttributeValues: {
        ":postId": event.body.id

      },

     

    }
1

There are 1 answers

5
Jatin Mehrotra On

As per comments.

you need to remodel your table design by using composite key structure.

composite key = email = hash key, postId =  range/sort key

note:- if you are using post-operation to query DB, event.body.id should be req.body.id.

you can simply use dynamodb get operation to grab single record

const getRecordParams = {
    TableName: tableName,
    Key: {
      email: req.body.id,    // hash key
      postId: req.body.postId  //range key
    },
  };
const dynamoDbGetResults = await dynamoDb
      .get(getRecordParams)
      .promise();

dynamoDbGetResults will have your entire record from which you can extract your desired values.

Note:- if you have constraints in changing table design an alternate solution would be to create index based on postId. Using that you can query directly on index using postId. dynamoDb supports local secondary index and Global secondary Index. they both have difference in terms of pricing, finding differences between them priorly for your use case would be good. https://stackoverflow.com/a/21383613/13126651