1

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!

Restir
  • 129
  • 4
  • 12

1 Answers1

3

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.

jarmod
  • 71,565
  • 16
  • 115
  • 122
  • Great! It works fine! Thank you! But I got one more question. My Items got categories and now I'm using one GSI to get all posts in one category. Am I able to add multiple GSI? I want to take 3 items from the newest created date with one category. – Restir Jul 15 '20 at 18:33
  • Yes, you can have multiple GSIs. – jarmod Jul 15 '20 at 18:35