Restir
Restir

Reputation: 149

How to sort asc by created date in dynamodb with documentClient

I just want to ask you, how can I receive the newest items sorted by ASC by created date.

const getItems = async (limit) => {
  const params = {
    TableName,
    KeyConditionExpression: '#field = :value',
    ExpressionAttributeNames: {
      '#field': 'pk',
    },
    ExpressionAttributeValues: {
      ':value': 'ITEM'
    },
    Limit: 3,
    ScanIndexForward: true, // I think that it will sort by date, but it's probably sorting by pk...
  };

  return results.Items;
};

How can I receive 3 newest created items with dynamodb documentClient?

Thank you for help!

Upvotes: 1

Views: 1764

Answers (1)

jarmod
jarmod

Reputation: 78583

The typical solution, assuming that you want the item with the latest date regardless of other attributes, is to create a Global Secondary Index with a composite primary key, where the partition key is a constant value and the sort key is the relevant date attribute.

Then you can make a query against the GSI with:

  • partition key = constant value
  • ScanIndexForward = false (to sort descending)
  • Limit = 1 (to retrieve 1 item only)

If you wanted the latest record of a given type, then the partition key in your query would be the type value.

Upvotes: 3

Related Questions