4

I have a table with a primary key and a sort key; since this is a composite key, I have multiple primary keys mapped with different sort keys.

How can I get all of the sort keys associated with a particular primary key?

I tried using the "Get" operation, but that seems to expect the sort key as well (even though these are what I'm looking for). I also looked at the "BatchGet" operation, but this is for multiple different keys, not for a single primary key with multiple different sort keys.

I tried to do "query" as well and wasn't successful, but I understand this less, so it's possible this is the solution -- is that the case? I am also aware that I could "scan" the entire database and specifically find all items with that particular primary key, but I'm looking to avoid this if possible.

I am working with JS and using this as a reference: https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html.

Thank you!

zpChris
  • 98
  • 1
  • 8
  • 1
    You can use `query` method, If the result of `query` includes `LastEvaluatedKey`, this mean you have more data to fetch, let put `LastEvaluatedKey` value to next query to get the next data, repeat again until `LastEvaluatedKey` is null or undefined. – hoangdv Dec 27 '19 at 03:18

1 Answers1

6

Query() is what you want...

Basically, you just query the table (or index) with a keycondition of HashKey = :hkey and leave off any AND of sort key conditions...

In the docs you linked to, there's a section for query modifying that example...

var params = {
  TableName: 'Table',
  KeyConditionExpression: 'HashKey = :hkey',
  ExpressionAttributeValues: {
    ':hkey': 'key'
  }
};

var documentClient = new AWS.DynamoDB.DocumentClient();

documentClient.query(params, function(err, data) {
   if (err) console.log(err);
   else console.log(data);
});
Charles
  • 21,637
  • 1
  • 20
  • 44
  • Would that return the sort key only or the entire document? Would it be the same in terms of performance if the data stored in the sort key was in an attribute? Could you use the same query in that case? – Kappacake Jan 30 '23 at 19:34