amazon-dynamodbamazon-dynamodb-streams

How to get sorted data from dynamodb based on dynamic column


I have a table in Dynamodb named "user" which has two columns, one is "time" and another is "cost".

I wanted to get the sorted data based on the column name, say if I provide input param as "time" the top 50 record in ascending order and if I provide input param as "cost" then top 50 record.

I have tried something like this, but this is not working.

{
    TableName: "User",
    Limit: 50,
    ScanIndexForward: false,
    ExclusiveStartKey: (params.lastEvaluatedKey)? {tripId: {S: String(params.lastEvaluatedKey)}}: null,
    KeyConditionExpression   : 'cost > :costValue',
    ExpressionAttributeValues : {
       ':costValue': '1'
    }
}

Solution

  • Unfortunately, Dynamodb doesn't have sort functionality to all the attributes in a table. You can sort the items by sort key only using ScanIndexForward is true/false.

    If you want to sort the items by attributes other than sort key, you have to do at client side (I.e. Dynamodb doesn't have this functionality).