Map order is not preserved in DynamoDB

Viewed 637

Via a JavaScript lambda function, I'm inserting an item into DynamoDB.

const item = {
 z: ..,
 x: ...,
 y: ...
}

If I look into the table after the put operation, I see that the properties have been sorted alphabetically.

const item = {
 x: ..,
 y: ...,
 z: ...
}

The developer guide mentions this behaviour, but for a Set, not for a Map. Is there a way to make DynamoDB preserve the Map order?

In our application, the user gives us this data. It's a bit odd to display back its data in a different order...

2 Answers

Maps/hashtables generally do not have any order, and in DynamoDB Maps are unordered. If you want order, you can use a List.

Per the documentation for Map:

A map type attribute can store an unordered collection of name-value pairs. Maps are enclosed in curly braces: { ... }

I know I'm late to answer this but still posting my solution here for someone who need may this in future.

I was in a similar kind of situation where order of data was very important but unfortunately we realised it bit late and at that time it was not feasible to change the DB.

so as a solution what I did , I added one more property called strItem in the map (JSON data coming from front-end). The strItem is added at the backend before pushing data in dynamoDB which contains stringifed map data.

for example this object you are getting from front-end

let data = 
{
  userId:101,
  name:"John doe",
  age:25,
  country: "India"
}

now add one more field(strItem) in the JSON which you are going to store in DB

data.strItem = JSON.stringify(data)

finally , your map looks like this-

{
  userId:101,
  name:"John doe",
  age:25,
  country: "India",
  strItem: '{"userId":101,"name":"John doe","age":25,"country":"India"}'
}

The reason why I'm suggesting to add strItem in the existing object because if you will replace the data with stringified data it will save storage for sure but then you won't be able to perform any kind of query operation in DB.

Every time when someone sends GET request for the given id, just fetch strItem from the DB and at backend perform JSON.parse(strItem). Finally return the parsed strItem as a response. In this way order of the data will be preserved.

Few things to take care of while using JSON.stringify() -

JSON.stringify({ key: NaN });
JSON.stringify({ key: Infinity });
// will be converted to "{"key": null}"


JSON.stringify({ key: undefined });
// will be converted to just "{}"
Related