Home > Blockchain >  Array or Map is better in database?
Array or Map is better in database?

Time:11-13

I am using AWS dynamoDB.

option 1

[{"id":"01","avaliable":true},
{"id":"02","avaliable":true},
{"id":"03","avaliable":false},
{"id":"04","avaliable":true}
{"id":"05","avaliable":false}]

option 2

"avaliable":[true,true,false,true,false]

id will always in sequence and start with 0 so I think it is a waste to include "id" as attribute. I can just update avaliabe in option 2 using {id-1} as array index. But I am not sure will there be any other issue if I use option 2. I am orginally using option 1 and will check whether the id correct before update. I am afraid option 2 will have mistake easily.

Which structure do you think is better?

CodePudding user response:

Personally I prefer to use Map type in DynamoDB because it allows you to update on a key versus guessing what index you need in an array. However that would be option 3:

"mymap":{
       "id01":{"avaliable":true},
       "id02":{"avaliable":true},
       "id03":{"avaliable":true},
       "id04":{"avaliable":true},
       "id05":{"avaliable":true}
     }

This allows you up modify elements without first trying to figure out what position in an array it might be, which sometimes requires you to first read the item and can cause concurrency issues.

I do notice you mention that you equate the position of the item in the array, however I feel this is a more fool-proof way for general implementation. For example, if you need to remove a value from the middle of the list, it would not cause any issues.

That is one thing that can influence your decision, the other 2 being item size and total storage.

If your item size is substantially less than 1KB then you will have no issue using option 1 or 3 which will increase your item size slightly compared to option 2. As long as the extra characters do not push your average item size over the nearest 1KB value as that will mean that you will have increased your capacity consumption for write requests.

The other being the total storage size. DynamoDB provides a free tier of 25GB of storage. If you have millions of items causing you to increase your storage size substantially, then you may decide to use option 2.

  • Related